我有以下列表:
seqList = [0, 6, 1, 4, 4, 2, 4, 1, 7, 0, 4, 5]
我只希望在列表中的项存在一次以上(在本例中为值1和4)并且要忽略列表中的第一个值(在本例中为0)时才打印列表中的项
要计算每个值出现在列表中的次数,我有以下代码:
from collections import Counter
seqList = [0, 6, 1, 4, 4, 2, 4, 1, 7, 0, 4, 6]
c = dict(Counter(seqList))
print(c)
带有输出:
{0: 2, 6: 1, 1: 2, 4: 4, 2: 1, 7: 1, 5: 1}
但是我想忽略除1和4之外的所有内容,并且列表中的前0不应该计数。
我要打印的输出是:
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)
有人知道我该如何实现吗?
您可以进行以下调整:
c = Counter(seqList[1:]) # slice to ignore first value, Counter IS a dict already
# Just output counts for 1 and 4
for i in (1, 4):
print('-value {} appears multiple times ({} times)'.format(i, c[i]))
# output
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)
一个具有列表理解力的好单线看起来像这样:
[print(f'- value {k} appears multiple times ({v} times)') for k, v in c.items() if v > 1]