我是Python的新手,还是Stackoverflow的新手,有人可以告诉我比较两个以上列表的有效(pythonic)方法吗?我要列出所有3个列表的所有元素,并以这种方式显示,以便用户将能够知道哪个元素存在于列表1中的所有3个列表OR元素中,而不是列表2中的OR元素,或者哪些元素是重复的。我已经完成了使用嵌套循环的比较。
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
有没有更好的方法来比较列表?
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
使用熊猫,您可以比较多个列表,而空的对话框将自动填充为NaN。
Pandas是python的数据可视化库
通过以下方式安装熊猫:pip install pandas
编辑:
要点链接:https : //gist.github.com/gr8Adakron/b51cc060b5e6dcc030261586f7237232
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句