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

Fer*_*ire 2 python for-loop list python-3.x

我试图遍历文本文件中的列,其中每个条目只有三个选项 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]

Kar*_*mar 7

这是您需要的set()

>>> lst1 = ['A','A','A','B','C','C','D','D','D','B','B']
>>> list(set(lst1))
['A', 'B', 'D', 'C']
Run Code Online (Sandbox Code Playgroud)

OrderedDict在插入过程中保持键顺序的另一种解决方案。

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lst1))
['A', 'B', 'C', 'D']
Run Code Online (Sandbox Code Playgroud)

如果您有使用熊猫的自由,请尝试以下熊猫。

>>> import pandas as pd
>>> drop_dups  = pd.Series(lst1).drop_duplicates().tolist()
>>> drop_dups
['A', 'B', 'C', 'D']
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找两个文件之间的通用值:

$ 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)
Run Code Online (Sandbox Code Playgroud)


小智 6

set在python中调用的数据结构不允许重复.这可能会帮助你.

docs.python.org上set()的文档