1.合并的方法:
(1).用 “+” 号:
list1 = ['a', 'b', 'c'] list2 = ['d', 'e'] list1 = list1 + list2 print(list1)
#list1 = ['a', 'b', 'c', 'd', 'e']
(2). 使用extend方法:
list1 = ['a', 'b', 'c'] list2 = ['d', 'e'] list1.extend(list2) print(list1)
(3). 使用切片:
list1 = ['a', 'b', 'c'] list2 = ['d', 'e'] list1[len(list1):len(list1)] = list2 print(list1)
2.获取list里面元素的下标:
(1). 使用index方法:
a = ['foo', 'bar', 'baz'] print(a.index('bar'))
(2). 使用enumerate方法:
a = ['foo', 'bar', 'baz'] print([i for i, x in enumerate(a) if x == 'bar'])
3.获取列表中随机的一个元素:
(1). 使用 random模块的choice方法随机选择某个元素:
from random import choice foo = ['a', 'b', 'c', 'd', 'e'] print(choice(foo))
(2).使用 random模块的sample方法随机选择一组元素:
import random
foo = ['a', 'b', 'c', 'd', 'e']
# 5次抽取3个元素
for i in range(5):
boo = random.sample(foo, 3)
print(boo)
# boo = random.sample(foo, 1)
# print(boo)