Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从列表中仅获取不同的值?_Python_Python 3.x_List_For Loop - Fatal编程技术网

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

Python 如何从列表中仅获取不同的值?,python,python-3.x,list,for-loop,Python,Python 3.x,List,For Loop,我试图遍历文本文件中的一列,其中每个条目只有三个选项a、B和C 我想确定不同类型选择的数量(另一个文本文件有A、B、C和D),但是如果我用100个条目迭代列中的每个元素,并将其添加到列表中,我会对每种类型重复多次。例如,如果我这样做,列表可能会显示[A,A,B,C,C,D,D,D,B,B…],但我想删除无关的条目,让列表显示可区分的类型[A,B,C,D],而不管有多少条目 有没有办法将一个包含许多公共元素的列表简化为只显示不同可区分元素的列表?谢谢 期望输出: [A,B,C,D]python中有

我试图遍历文本文件中的一列,其中每个条目只有三个选项
a、B和C

我想确定不同类型选择的数量
(另一个文本文件有A、B、C和D)
,但是如果我用
100个条目迭代列中的每个元素,并将其添加到列表中,我会对每种类型重复多次。例如,如果我这样做,列表可能会显示
[A,A,B,C,C,D,D,D,B,B…]
,但我想删除无关的条目,让列表显示可区分的类型
[A,B,C,D]
,而不管有多少条目

有没有办法将一个包含许多公共元素的列表简化为只显示不同可区分元素的列表?谢谢

期望输出:


[A,B,C,D]
python中有一个名为
set
的数据结构,不允许重复。 这可能对你有所帮助

我们可以使用itertools.groupby和
排序
来获取此唯一元素列表

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']
这就是使用
set()
所需的: 另一种解决方案是在插入过程中保持键的顺序。 如果你有自由使用熊猫,那么试试下面的。。 如果要查找两个文件之间的公共值:

$ 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)

如果您发布了一段
txt
和您需要的任何代码,将会有所帮助attempted@Ferreroire,如果您觉得可以解决您的要求,您可以接受答案和upvote,这样它将从未回答的队列中删除。非常感谢!这很有帮助!
>>> 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)