Agsthya
Agsthya

Reputation: 33

Compare 2 lists and print the element of the 2nd list if it is present in first list, but not by using 2 for loops

I have to compare 2 lists, if element of list a is present in list b, then the element of list b is to print.

a = [1, 3, 2, 1, 3]
b = [2, 2, 1, 1, 1, 4, 2, 3]

ans = [1, 1, 1, 3, 2, 2, 2, 1, 1, 1, 3]

I may get the answer by using 2 for loops like:

for a_ in a:
    for b_ in b:
        if a_ == b_: 
            print b_

op: 1 1 1 3 2 2 2 1 1 1 3

But I don't want to use 2 for loops. How can I do that with a single loop?

Upvotes: 2

Views: 119

Answers (4)

vathek
vathek

Reputation: 551

This, should be work:

for a_ in a:
    if b.count(a_) :
         ans+=((str(a_)+' ')*b.count(a_)).strip().split(' ')

list.count(x) count the number of occourrences of x in list.

you can print n times a string simply: *'mystring'times

Hope I helped you!

Upvotes: 0

zondo
zondo

Reputation: 20336

print(" ".join(str(x) for x in a for _ in range(b.count(x))))

Upvotes: 0

Peter
Peter

Reputation: 3495

This is one potential way (a bit messy), just posting it since it turns out Fabricator didn't end up with the correct result.

[item for sublist in ([i] * b.count(i) for i in a) for item in sublist]

Basically, the ([i] * b.count(i) for i in a) part builds the list, but it ends up as a list of lists, so then I did the [item for sublist in list for item in sublist] thing to flatten the list.

It's probably a bit similar to the answer by zondo but this keeps it as a list of numbers instead of a string.

Upvotes: 1

Fabricator
Fabricator

Reputation: 12772

Use collections.Counter to count for you:

from collections import Counter
c = Counter(b)
ans = []
for x in a:
    ans += [x]*c.get(x,0)

Upvotes: 1

Related Questions