获取列表中只出现两次不超过两次的元素的值

get the values of elements in the list which occurs only twice not more than twice

我有一个元素列表我想存储列表中只出现两次不超过两次或少于twice.Below的元素是列表

list = [595, 595, 344, 344, 628, 628, 628, 353, 353, 353, 353, 353]

从列表中我希望输出为 result = [595,344]

下面的代码returns只有一个元素

def has1dup(lst):
    setlst = list(set(lst)) # no duplicate elements
    for i in range(len(setlst)): # while the setlist's element count, 
        if lst.count(setlst[i]) > 1: # if the count of setlist[i] of lst is bigger than 1
            return setlst[i] # return it

您需要创建一个结果列表,并将 setlst[i] 附加到结果列表,而不是立即 returning 它。然后,return结果列表。

这里用这个:

lst2 = list(set([x for x in lst if lst.count(x)==2]))

如果您不想更改顺序,请使用此选项:

lst = [595, 595, 344, 344, 628, 628, 628, 353, 353, 353, 353, 353]
lst2=[]
[lst2.append(x) for x in lst if lst.count(x)==2 and x not in lst2]
print(lst2)

您缺少第二个元素,因为您使用的是 return 语句。

而是使用如下内容

mylist = [595, 595, 344, 344, 628, 628, 628, 353, 353, 353, 353, 353]
newlist = []
def has1dup(lst):
    setlst = list(set(lst)) # no duplicate elements
    for i in range(len(setlst)): # while the setlist's element count,
        if lst.count(setlst[i]) == 2: # if the count of setlist[i] of lst is bigger than 1
            newlist.append(setlst[i])

has1dup(mylist)
print(newlist)

输出

[344, 595]

现在在上面的例子中我们已经声明了一个名为 newlist 的新列表。对于集合中其在列表中的计数恰好为 2 的每个元素,我们将其附加到新列表。

您可以利用 collections 中的 Counter

例如

>>> from collections import Counter
>>> l = [595, 595, 344, 344, 628, 628, 628, 353, 353, 353, 353, 353]
>>> new_dict=Counter(l)
>>> new_dict
Counter({353: 5, 628: 3, 595: 2, 344: 2})
>>> [key for key, val in new_dict.items() if val == 2]
[595, 344]