user2978216
user2978216

Reputation: 568

For loops into List comprehensions

I'd like to print any number that appears more than once. How do I change my for loops into list comprehensions?

from collections import Counter
cnt=Counter()
in1="4 8 0 3 4 2 0 3".split(" ")
for elt in in1:
    cnt[elt]+=1
more_than_one=[]
for value, amount in cnt.items():
    if amount > 1: more_than_one.append(value)
print(*more_than_one)

Desirable output: 4 0 3

Upvotes: 1

Views: 121

Answers (2)

jamylak
jamylak

Reputation: 133744

>>> from collections import Counter
>>> text = "4 8 0 3 4 2 0 3"
>>> counts = Counter(text.split())
>>> valid = [k for k in counts if counts[k] > 1]
>>> valid
['4', '0', '3']

Upvotes: 1

RoadRunner
RoadRunner

Reputation: 26335

Instead of counting the values yourself:

cnt=Counter()
in1="4 8 0 3 4 2 0 3".split(" ")
for elt in in1:
    cnt[elt]+=1

You can simply pass in1 to collections.Counter() to do all the counting for you:

cnt = Counter(in1)

As for turning your code into a list comprehension, you can try this:

from collections import Counter

in1="4 8 0 3 4 2 0 3".split()

cnt = Counter(in1)

print([k for k, v in cnt.items() if v > 1])

Which Outputs:

['4', '0', '3']

Note: You also don't need to pass " " to split(), since it defaults to white space.

Upvotes: 7

Related Questions