赞
踩
append()
追加元素列表In [22]:list1 = []
In [23]:list1.append(1)
In [24]:list1.append(4)
In [25]:list1
Out[25]: [1, 4]
In [27]:list1 = [1, 4, 8, 32]
In [28]:list1[2] = 16
In [29]:list1
Out[29]: [1, 4, 16, 32]
In [30]:list1[0:2] = [100, 400]
In [31]:list1
Out[31]: [100, 400, 16, 32]
remove()
删除列表指定元素 - 按值删除In [31]:list1
Out[31]: [100, 400, 16, 32]
In [32]:list1.remove(400)
In [33]:list1
Out[33]: [100, 16, 32]
del
删除列表指定元素 - 按索引删除In [33]:list1
Out[33]: [100, 16, 32]
In [34]:del list1[1]
In [35]:list1
Out[35]: [100, 32]
insert()
在列表指定位置插入新元素In [35]:list1
Out[35]: [100, 32]
In [36]:list1.insert(1, 300)
In [37]:list1
Out[37]: [100, 300, 32]
# 如果指定位置超出列表范围,会把元素追加到列表后面
In [38]:list1.insert(88, 300)
In [39]:list1
Out[39]: [100, 300, 32, 300]
In [1]:list1 = [1, 3, 5]
In [2]:list2 = [2, 4, 6]
In [3]:list1 + list2
Out[3]: [1, 3, 5, 2, 4, 6]
In [16]:list1 = ['瓦坎达', 'forever']
In [17]:list1 * 3
Out[17]: ['瓦坎达', 'forever', '瓦坎达', 'forever', '瓦坎达', 'forever']
In [18]:list1 * 0
Out[18]: []
In [19]:list1 * (-1)
Out[19]: []
names = ['红塔山', '煊赫门', '云烟']
name = input('输入待查名字:')
if name in names:
print('{}在列表里'.format(name))
else:
print('{}不在列表里'.format(name))
输出结果:
输入待查名字:玉溪
玉溪不在列表里
输入待查名字:云烟
云烟在列表里
In [20]:list1
Out[20]: ['瓦坎达', 'forever']
In [21]:list2 = list1.copy()
In [22]:list2
Out[22]: ['瓦坎达', 'forever']
[新列表元素构成的表达式 for 新列表元素 in 旧列表 if <表达式>]
nums = [5, 6, 2, 8, 11, 25]
odds = [x for x in nums if x % 2 == 1]
evens = [x for x in nums if x % 2 == 0]
print(odds)
print(evens)
输出结果:
[5, 11, 25]
[6, 2, 8]
nums = [5, 6, 2, 8, 11, 25]
new_nums = [x * 2 for x in nums]
print(new_nums)
输出结果:
[10, 12, 4, 16, 22, 50]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。