我是Python新手,也是Stackoverflow的新手,有人能告诉我有效(pythonic)方法来比较超过2个列表吗?我想要列出所有3个列表的所有元素,并以这样的方式显示,用户将能够知道列表1中存在的所有3个列表OR元素中存在哪个元素,但列表2中没有,或者哪些元素是重复的。我已经使用嵌套循环进行了比较。
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
# Checking whether List 1 value present in List2 and List 3
for l1 in List1:
if l1 in List2:
List2.remove(l1)
if l1 in List3:
List3.remove(l1)
print(l1," ",l1," ",l1)
else:
print(l1," ",l1," ","NA")
else:
if l1 in List3:
List3.remove(l1)
print(l1," ","NA"," ",l1)
else:
print(l1," ","NA"," ","NA")
# Checking whether List 2 value present in List3
for l2 in List2:
if l2 in List3:
List3.remove(l2)
print("NA"," ",l2," ",l2)
else:
print("NA"," ",l2," ","NA")
# Checking for values present only in List 3
for l3 in List3:
print("NA","NA",l3)
--- Output---
List1 List2 List3
10 10 10
10 NA NA
11 11 11
12 NA 12
15 15 15
16 16 NA
18 NA NA
19 19 19
NA 13 NA
NA 20 NA
NA NA 11
NA NA 21
NA NA 23
NA 20 NA
NA NA 11
NA NA 21
NA NA 23
有没有更好的方法来比较列表?
答案 0 :(得分:4)
import pandas as pd
d = {'List1' : pd.Series(List1),'List2' : pd.Series(List2),'List3': pd.Series(List3)}
df = pd.DataFrame(d)
print(df)
***OUTPUT:***
List1 List2 List3
10 NaN NaN
11 11 11
12 NaN 12
15 15 15
16 16 NaN
18 NaN NaN
19 19 19
NaN 13 NaN
使用Pandas可以比较多个列表,而空的coloumn将自动填充为NaN。
Pandas是python的数据可视化库
通过以下方式安装pandas:pip install pandas
编辑:
Gist Link:https://gist.github.com/gr8Adakron/b51cc060b5e6dcc030261586f7237232
答案 1 :(得分:3)
如果您想要所有列表的交集,请设置一个并将其他列表传递给File file2=new File(Environment.getExternalStorageDirectory(), "//test2");
file2.mkdir();
System.out.println(file2.canWrite());
:
.intersection
这给了你:
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
print(set(List1).intersection(List2, List3))
从List3获取唯一元素:
set([19, 10, 11, 15])
如果您只想保留每个列表中不在交集中的元素:
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
inter = set(List1).intersection(List2, List3)
diff3 = set(List3).difference(inter)
print(diff3)
set([12, 21, 23])
哪个会给你:
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
inter = set(List1).intersection(List2, List3)
List1[:] = [ele for ele in List1 if ele not in inter]
List2[:] = [ele for ele in List2 if ele not in inter]
List3[:] = [ele for ele in List3 if ele not in inter]
print(List1)
print(List2)
print(List3)
答案 2 :(得分:1)
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
>>> set(List1).intersection(set(List2))
set([16, 19, 10, 11, 15])
>>> set(List1).intersection(set(List3))
set([19, 10, 11, 12, 15])
>>> set(List2).intersection(set(List3))
set([19, 10, 11, 15])
>>>
交叉产生两组中的数字。 Set包含列表中的不同值,没有重复
关于您是否要考虑重复,我的问题不清楚,如果是这样的话。