如何仅从列表中获取不同的值?

时间:2018-10-06 17:45:15

标签: python python-3.x list for-loop

我正在尝试遍历文本文件中的一列,其中每个条目只有三个选择A, B, and C

我想确定不同类型的选择(another text file has A, B, C, and D)的数量,但是如果我用100 entries遍历列中的每个元素并将其添加到列表中,我将有多次重复每种类型。例如,如果执行此操作,则列表可能显示为[A,A,A,B,C,C,D,D,D,B,B...],但是我想删除无关的条目,而只让我的列表显示可区分的类型[A,B,C,D],而不管有多少个条目。

有什么想法可以将包含许多常见元素的列表简化为仅显示不同元素的列表?谢谢!

所需的输出:

[A, B, C, D]

3 个答案:

答案 0 :(得分:6)

python中有一个名为set的数据结构,不允许重复。 这可能会帮助您。

documentation for set() at docs.python.org

答案 1 :(得分:4)

这是您使用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)

答案 2 :(得分:0)

我们可以使用 itertools.groupby sorted来获取唯一元素列表

from itertools import groupby

with open('text.txt') as f:
    content = [line.strip('\n') for line in f]

l = [k for k, g in groupby(sorted(content))]
print(l)
# ['A', 'B', 'C', 'D']
相关问题