赞
踩
x = [0 for i in range(5)]
print(x, type(x))
[0, 0, 0, 0, 0] <class ‘list’>
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x, type(x))
[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99] <class ‘list’>
此元素如果是一个 list,那么这个 list 将作为一个整体进行追加,注意**append()和extend()**的区别。
x = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
x.append([‘Thursday’, ‘Sunday’])
print(x)
[‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, [‘Thursday’, ‘Sunday’]]
x = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
x.extend([‘Thursday’, ‘Sunday’])
print(x)
#[‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Thursday’, ‘Sunday’]
x = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
x.insert(2, ‘Sunday’)
print(x)
[‘Monday’, ‘Tuesday’, ‘Sunday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
x = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
x.remove(‘Monday’)
print(x) [‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
x = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
y = x.pop()
print(y) # Friday
y = x.pop(0)
print(y) # Monday
y = x.pop(-2)
print(y) # Wednesday
print(x) # [‘Tuesday’, ‘Thursday’]
x = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
del x[0:2]
print(x) # [‘Wednesday’, ‘Thursday’, ‘Friday’]
通过元素的索引值,从列表获取单个元素,注意,列表索引值是从0开始的。
通过将索引指定为-1,可让Python返回最后一个列表元素,索引 -2 返回倒数第二个列表元素,以此类推。
list1 = [123, 456, 789, 213]
list2 = list1
list3 = list1[:]
print(list2) # [123, 456, 789, 213]
print(list3) # [123, 456, 789, 213]
list1.sort()
print(list2) # [123, 213, 456, 789]
print(list3) # [123, 456, 789, 213]
list1 = [[123, 456], [789, 213]]
list2 = list1
list3 = list1[:]
print(list2) # [[123, 456], [789, 213]]
print(list3) # [[123, 456], [789, 213]]
list1[0][0] = 111
print(list2) # [[111, 456], [789, 213]]
print(list3) # [[111, 456], [789, 213]]
等号操作符:==
连接操作符 +
重复操作符 *
成员关系操作符 in、not in
「等号 ==」,只有成员、成员位置都相同时才返回True。
列表拼接有两种方式,用「加号 +」和「乘号 *」,前者首尾拼接,后者复制拼接。
key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse – 排序规则,reverse = True 降序, reverse = False 升序(默认)。
该方法没有返回值,但是会对列表的对象进行排序。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。