我有以下清单:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
{0: 2, 6: 1, 1: 2, 4: 4, 2: 1, 7: 1, 5: 1}
Run Code Online (Sandbox Code Playgroud)
但是我想忽略除1和4之外的所有内容,并且列表中的前0不应该计算在内。
我要打印的输出是:
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)
Run Code Online (Sandbox Code Playgroud)
有谁知道我如何实现这一目标?
您可以进行以下调整:
c = Counter(seqList[1:]) # slice to ignore first value, Counter IS a dict already
# Just output counts > 1
for k, v in c.items():
if v > 1:
print('-value {} appears multiple times ({} times)'.format(k, v))
# output
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)
Run Code Online (Sandbox Code Playgroud)