Reputation: 33
I have two lists. I need to compare elements whether any element in the list is matching or not. Input:
a = ['1001,1715']
b = ['1009,1715']
Output : 1715
Please suggest how to do it? I tried doing:
set(''.join(a))
and
set(''.join(b))
but it gave me {'5', '0', '7', ',', '1'}
. how can I convert ['1001,1715']
to [1001,1715]
?
Upvotes: 3
Views: 149
Reputation: 12417
A more general solution if you have lists with more elements (e.g a = ['1001,1715','1009,2000']
)
a = [x for xs in a for x in xs.split(',')]
b = [x for xs in b for x in xs.split(',')]
common = set(a).intersection(set(b))
Example:
a = ['1001,1715','1009,2000']
b = ['1009,1715']
Output:
{'1009', '1715'}
Upvotes: 0
Reputation: 5699
a = ['1001,1715']
b = ['1009,1715']
def fun(a):
return a[0].split(",")
def intersect(a, b):
return list(set(a) & set(b))
print(intersect(fun(a),fun(b)))
Upvotes: 2
Reputation: 164623
There are 2 parts to your problem.
Convert strings to sets of integers
Since your string is the only element of a list, you can use list indexing and str.split
with map
:
a_set = set(map(int, a[0].split(',')))
b_set = set(map(int, b[0].split(',')))
Calculate the intersection of 2 sets
res = a_set & b_set
# alternatively, a_set.intersection(b_set)
print(res)
{1715}
Upvotes: 0
Reputation: 45309
You can use set intersection:
set(a[0].split(',')).intersection(set(b[0].split(',')))
Which returns:
{'1715'}
Converting from '1001,1715'
to ['1001', '1715']
can simply be done with .split(',')
Upvotes: 0