简体   繁体   中英

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)

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM