简体   繁体   English

仅当它们在 python 的列表中出现多次时,我如何打印值

[英]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.

相关问题 如何防止嵌套列表中的元素出现多次? - How do I prevent elements in a nested list to appear more than once? Python 如何按顺序多次打印列表? - Python how to print a list more than once but in order? 如果最大的数字在同一个列表中多次出现,我如何将它们全部打印出来? - If the largest number occurs more than once in the same list, how do I print them all out? 如何在不使用python中的多个if / else语句的情况下多次生成随机列表? - How do I generate a random list more than once without using multiple if/else statements in python? 查找出现多次的值的键 - Find keys for values that appear more than once 刽子手问题:当输入的字母不存在时,如何重置循环?如何让字母在单词中出现多次? - Hangman Issue: How do I make my loop reset when the letter entered is not present and how do I make the letter appear more than once in the word? Python不会打印超过12个有效数字。 如何更轻松地打印? - Python won't print more than 12 significant figures. How do I print more easily? 当只有一些变量需要多个变量时,如何将多个值传递给函数-Python 3 - How can I pass multiple values to a function when only some variables need more than one - python 3 在Python中一定数量的字符出现多于一次之后,如何修剪字符串? - How do I trim a string after certain amount of characters appear more then once in Python? 如果列表python中有两个以上的值,则以逗号分隔 - print comma separated if more than two values in the list python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM