How to get only distinct values from a list?
本问题已经有最佳答案,请猛点这里访问。
我试图遍历文本文件中的一列,其中每个条目只有三个选项
我想确定
我有什么想法可以把一个有许多公共元素的列表简化成只显示不同可分辨元素的列表吗?谢谢!
期望输出:
埃多克斯1〔5〕
python中有一个名为
docs.python.org上set()的文档
这是您对
1 2 3 | >>> lst1 = ['A','A','A','B','C','C','D','D','D','B','B'] >>> list(set(lst1)) ['A', 'B', 'D', 'C'] |
号另一个解决方案是
1 2 3 | >>> from collections import OrderedDict >>> list(OrderedDict.fromkeys(lst1)) ['A', 'B', 'C', 'D'] |
如果你有使用熊猫的自由,那么试试下面的。
1 2 3 4 | >>> import pandas as pd >>> drop_dups = pd.Series(lst1).drop_duplicates().tolist() >>> drop_dups ['A', 'B', 'C', 'D'] |
。
如果要查找两个文件之间的公共值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $ 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(' '.join(s.strip(' ') 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) |
我们可以使用itertools.groupby和
1 2 3 4 5 6 7 8 9 | from itertools import groupby with open('text.txt') as f: content = [line.strip(' ') for line in f] l = [k for k, g in groupby(sorted(content))] print(l) # ['A', 'B', 'C', 'D'] |