python - 如何从列表中仅获取不同的值?
问题描述
我正在尝试遍历文本文件中的一列,其中每个条目只有三个选项 A, B, and C
。
我想确定不同类型选择的数量(another text file has A, B, C, and D)
,但是如果我用 a 遍历列中的每个元素100 entries
并将其添加到列表中,我将对每种类型进行多次重复。例如,如果我这样做,列表可能会读取[A,A,A,B,C,C,D,D,D,B,B...]
,但我想删除无关的条目并让我的列表显示可区分的类型[A,B,C,D]
,而不管有多少条目。
有什么想法可以将包含许多常见元素的列表简化为仅显示不同可区分元素的列表吗?谢谢!
期望的输出:
[A, B, C, D]
解决方案
这是您需要的set()
:
>>> lst1 = ['A','A','A','B','C','C','D','D','D','B','B']
>>> list(set(lst1))
['A', 'B', 'D', 'C']
另一种OrderedDict
在插入过程中保持键顺序的解决方案。
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lst1))
['A', 'B', 'C', 'D']
如果您可以自由使用熊猫,请尝试以下熊猫..
>>> import pandas as pd
>>> drop_dups = pd.Series(lst1).drop_duplicates().tolist()
>>> drop_dups
['A', 'B', 'C', 'D']
如果您正在寻找两个文件之间的共同值:
$ cat getcomn_vals.py
#!/python/v3.6.1/bin/python3
def print_common_members(a, b):
"""
Given two sets, print the intersection, or "No common elements".
Remove the List construct and directly adding the elements to the set().
Hence assigned the dataset1 & dataset2 directly to set()
"""
print('\n'.join(s.strip('\n') for s in a & b) or "No common element")
with open('file1.txt') as file1, open('file2.txt') as file2:
dataset1 = set(file1)
dataset2 = set(file2)
print_common_members(dataset1, dataset2)