Reputation: 21
I am currently working on an exam project in python, where I have to make a choropleth map that shows all the different countries in the world, and what their populations are.
I get my data from an api and store that data in 2 different lists, let's call them a and b.
a contains values looking like this:
a = [['Afghanistan', 'AF'], ['Åland Islands', 'AX'], ['Albania', 'AL'], ['Algeria', 'DZ'], ['American Samoa', 'AS'], ['Andorra', 'AD'], ['Angola', 'AO']
and b:
b = ['Afghanistan' 'AFRICA' 'Albania' 'Algeria' 'Angola'
I want to create a new list named c that contains only the values, which appears in BOTH lists.
What confuses me the most, is that, "a" contains both country names and country codes, and "b" contains single values, listed next to each other.
list "c" should end up looking something like this: ['Afghanistan','Albania',Algeria','Angola']...
Thanks in advance
Upvotes: 0
Views: 83
Reputation: 143
i too new to python and i dont know the predefined functions and i write my logic to you. Hope this work for you ...
a = [['Afghanistan', 'AF'], ['Åland Islands', 'AX'], ['Albania', 'AL'], ['Algeria', 'DZ'], ['American Samoa', 'AS'], ['Andorra', 'AD'], ['Angola', 'AO']]
b = ['Afghanistan' ,'AFRICA', 'Albania' ,'Algeria', 'Angola']
c=[]
for i in range(0,len(b)):
for j in range(0,len(a)):
if(b[i]==a[j][0]):
c.append(b[i])
break
print(c)
have fun in python
Upvotes: 0
Reputation: 51165
You can flatten the first list using itertools.chain.from_iterable
and use set intersection:
>>> set(itertools.chain.from_iterable(a)) & set(b)
set(['Afghanistan', 'Albania', 'Angola', 'Algeria'])
If you don't want the itertools import (at the cost of a bit of performance):
>>> set([i for j in a for i in j]) & set(b)
set(['Afghanistan', 'Albania', 'Angola', 'Algeria'])
Upvotes: 2