[英]How do I print values only when they appear more than once in a list in python
I have the following list:我有以下清单:
seqList = [0, 6, 1, 4, 4, 2, 4, 1, 7, 0, 4, 5]
I want to print the items in the list only when it is present more than once(in this case value 1 and 4) and I want to ignore the first value in the list (in this case value 0)我只想在列表中的项目出现不止一次时才打印它(在本例中为值 1 和 4),并且我想忽略列表中的第一个值(在本例中为值 0)
To count how many times each value is present in the list I have the following code:为了计算列表中每个值出现的次数,我有以下代码:
from collections import Counter
seqList = [0, 6, 1, 4, 4, 2, 4, 1, 7, 0, 4, 6]
c = dict(Counter(seqList))
print(c)
with output:带输出:
{0: 2, 6: 1, 1: 2, 4: 4, 2: 1, 7: 1, 5: 1}
But I want to ignore everything but 1 and 4 And the first 0 in the list shouldn't count.但是我想忽略除 1 和 4 之外的所有内容,并且列表中的第一个 0 不应该计算在内。
The output I want to print is:我要打印的输出是:
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)
Does anyone have an idea how I could achieve this?有谁知道我如何实现这一目标?
You could make the following adjustments:您可以进行以下调整:
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)
一个很好的单行列表理解应该是这样的:
[print(f'- value {k} appears multiple times ({v} times)') for k, v in c.items() if v > 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.