myList=list("data")
print(myList)
[‘d’, ‘a’, ‘t’, ‘a’]
左闭右开
myList1[start:stop:step]
myList1[1:8:2]
myList1=[21,22,23,24,25,26,27,28,29]
myList1[:-1]
[21, 22, 23, 24, 25, 26, 27, 28]
myList1=[21,22,23,24,25,26,27,28,29]
myList1[::-1]
[29, 28, 27, 26, 25, 24, 23, 22, 21]
此时,myList1=[21,22,23,24,25,26,27,28,29]
切片操作不会改变列表本身
myList1=[21,22,23,24,25,26,27,28,29]
reversed(myList1) #reversed()函数的返回值为一个迭代器,可以用list()强制转换的方式显示其取值内容
list(reversed(myList1))
[29, 28, 27, 26, 25, 24, 23, 22, 21]
此时,myList1=[21,22,23,24,25,26,27,28,29]
内置函数reversed()不会改变列表本身
reversed(myList1)返回一个迭代器,需要用list()函数转换才能显示。
myList1=[21,22,23,24,25,26,27,28,29]
reversed(myList1)
print(reversed(myList1))
myList1=[21,22,23,24,25,26,27,28,29]
myList1.reverse() #内置函数reversed()与列表方法reverse()的区别:前者不改变列表本身,后者改变列表本身
myList1
[29, 28, 27, 26, 25, 24, 23, 22, 21]
列表方法reverse()改变列表本身
【1】列表的“+”运算
myList1=[21,22,23,24,25,26,27,28,29]
myList2=myList1
myList1+myList2
[21, 22, 23, 24, 25, 26, 27, 28, 29, 21, 22, 23, 24, 25, 26, 27, 28, 29]
myList1=[21,22,23,24,25,26,27,28,29]
myList2=myList1
myList1.extend(myList2)
myList1
[21, 22, 23, 24, 25, 26, 27, 28, 29, 21, 22, 23, 24, 25, 26, 27, 28, 29]
列表的“+”运算相当于列表的方法extend()
【2】列表的方法append()
myList1=[21,22,23,24,25,26,27,28,29]
myList2=myList1
myList1.append(myList2)
myList1
[21, 22, 23, 24, 25, 26, 27, 28, 29, […]]
列表的方法append()与extend()的区别:前者是“以成员身份追加”,而后者是“平等追加”
【3】两个列表的并列相加计算
myList1=[1,2,3,4,5,6,7,8,9]
myList3=[11,12,13,14,15,16,17,18,19]
[i+j for i,j in zip(myList1,myList3)]
[12, 14, 16, 18, 20, 22, 24, 26, 28]
[2 for i in range(20)]
#先做range(),再做i,最后做2
#注意:①列表推导式必须放在[]中;②for之前是一个表达式
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[i for i in range(1,21)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[i for i in range(1,21,2)]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
range(10)
range(0, 10)
[i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(0,10,2))
[0, 2, 4, 6, 8]
[type(item) for item in [True,"1",1,1.0]]
[bool, str, int, float]
["input/%d.txt"%i+"dd%d"%i for i in range(5)]
[‘input/0.txtdd0’,
‘input/1.txtdd1’,
‘input/2.txtdd2’,
‘input/3.txtdd3’,
‘input/4.txtdd4’]
在Python列表推导式中可以用字符串的占位符,如%d,用法类似C语言的print()、scanf()函数中的占位符
%d为占位符,在对应位置上显示的是“%i”的值
lst_1=[10,10,11,12,13,14,15]
lst_1.insert(1,8) #表示在下标为1的位置插入8
lst_1
[10, 8, 10, 11, 12, 13, 14, 15]
lst_1=[10,10,11,12,13,14,15]
lst_1.pop(2)
lst_1
[10, 10, 12, 13, 14, 15]
lst_1=[10,10,11,12,13,14,15]
del lst_1[2]
lst_1
[10, 10, 12, 13, 14, 15]
lst_1=[10,10,11,12,11,13,11,14,15]
for i in lst_1:
if i==10:
lst_1.remove(i)
print(lst_1)
[10, 11, 12, 11, 13, 11, 14, 15]
只删除第一个10,第二个10并未删除
lst_1=[10,10,11,12,11,13,11,14,15]
for i in lst_1:
if i==11:
lst_1.remove(i)
print(lst_1)
[10, 10, 12, 13, 14, 15]
删除了所有11
debug
lst = [10,11,11,12,11,13,11,14,15]
index = 0
for i in lst:
print(index)
if i==11