1. 已知 AList = [1,2,3,1,2],对 AList 列表元素去重,写出具体过程。
答:
AList = [1,2,3,1,2]
BList = set(AList)print(BList)
print(list(BList))
输出结果:
{1, 2, 3}
[1, 2, 3]
2. 如何实现 “1,2,3” 变成 [“1”,“2”,“3”]
答:
s = "1,2,3"
print(s.split(","))
输出结果:
['1', '2', '3']
3. 给定两个 list,A 和 B,找出相同元素和不同元素
答:
AList = [1,2,3,4,5]
BList = [4,5,6,7,8]
#找出相同元素
print(set(AList)&set(BList))
#找出不同元素
print(set(AList)^set(BList))
运行结果:
{4, 5}
{1, 2, 3, 6, 7, 8}
4. [[1,2],[3,4],[5,6]] 一行代码展开该列表,得出 [1,2,3,4,5,6]
答:
A = [[1,2],[3,4],[5,6]]
x=[j for i in A for j in i]
print(x)
运行结果:
[1, 2, 3, 4, 5, 6]
5. 合并列表 [1,5,7,9] 和 [2,2,6,8]
答:使用 extend 和 + 都可以。
a = [1,5,7,9]
b = [2,2,6,8]
a.extend(b)
print(a)
运行结果:
[1, 5, 7, 9, 2, 2, 6, 8]
6. 如何打乱一个列表的元素?
答:shuffle() 方法将序列的所有元素随机排序。
import randoma = [1, 2, 3, 4, 5]
random.shuffle(a)
print(a)
运行结果:
[3, 2, 5, 1, 4]