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

2024-03-29 15:42:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元素列表,我想将这些元素存储在列表中,这些元素只出现两次,不超过两次或少于两次

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

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

下面的代码只返回一个元素

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

Tags: ofthe代码元素列表returnifdef
3条回答

这里使用这个:

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)

您可以利用来自collectionsCounter

例如

>>> 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]

您缺少第二个元素,因为您正在使用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的每个元素,我们将其附加到一个新列表中

相关问题 更多 >