Reputation: 81
Problem:
I have a List of lists (lists_of_lists
), that each contain 5 floats in each list. I am trying to unpack lists_of_lists
and for every unpacked list, name it using the values in my country_list
Example of desired output:
Brazil = [28.42, 56.12, 59.97, 61.69, 60.34]
British = [39.1, 57.96, 56.29, 56.5, 71.25]
Note: the ordering in both lists correspond, as demonstrated above.
Resources:
list_of_lists = [[28.42, 56.12, 59.97, 61.69, 60.34], [39.1, 57.96, 56.29, 56.5, 71.25], [14.3, 42.33, 58.54, 41.24, 49.76]]
country_list = ['brazil', 'british', 'cantopop', 'mandopop', 'french', 'german', 'indian', 'iranian', 'malay', 'philippines-opm', 'spanish', 'swedish', 'turkish']
My thinking:
is that I should use a for loop to iterate through the country_list
and for every string (country name), create a new list and populate using the same positioned list in the list_of_lists
Any hints would be great. Thank you
Upvotes: 0
Views: 43
Reputation: 362
I would create a dict to store the results.
myDict = {}
for i in range(len(list_of_lists)):
myDict[country_list(i)] = list_of_lists(i)
Upvotes: 0
Reputation: 830
dict(zip(country_list, list_of_lists))
will give you a dictionary of country: list, as
{'brazil': [28.42, 56.12, 59.97, 61.69, 60.34], 'british': [39.1, 57.96, 56.29, 56.5, 71.25], 'cantopop': [14.3, 42.33, 58.54, 41.24, 49.76]}
As you can see the shortest element zipped is used (here country_list).
Upvotes: 3
Reputation: 51643
Creating "named" variables makes no sense. Put them into a dictionary:
list_of_lists= [[28.42, 56.12, 59.97, 61.69, 60.34],
[39.1, 57.96, 56.29, 56.5, 71.25],
[14.3, 42.33, 58.54, 41.24, 49.76]]
country_list = ['brazil', 'british', 'cantopop', 'mandopop', 'french',
'german', 'indian', 'iranian', 'malay', 'philippines-opm',
'spanish', 'swedish', 'turkish']
merger = {k:v for k,v in zip( country_list, list_of_lists)}
print(merger)
Output:
{'brazil': [28.42, 56.12, 59.97, 61.69, 60.34],
'british': [39.1, 57.96, 56.29, 56.5, 71.25],
'cantopop': [14.3, 42.33, 58.54, 41.24, 49.76]}
Shortest list wins. You can use the dictionary, to get all of brazils values:
print(merger["brazil"]) # [28.42, 56.12, 59.97, 61.69, 60.34]
To get all values iterate the dict:
for key in merger:
print(key)
print(merger[key])
Output:
brazil
[28.42, 56.12, 59.97, 61.69, 60.34]
british
[39.1, 57.96, 56.29, 56.5, 71.25]
cantopop
[14.3, 42.33, 58.54, 41.24, 49.76]
See:
Upvotes: 0
Reputation: 1417
enumerate
gives you iterator for both index and value
list_of_lists= [[28.42, 56.12, 59.97, 61.69, 60.34], [39.1, 57.96, 56.29, 56.5, 71.25], [14.3, 42.33, 58.54, 41.24, 49.76]]
country_list = ['brazil', 'british', 'cantopop']
# to print
for idx, country in enumerate(country_list):
print(country, list_of_lists[idx])
# to store in a dictionary:
d = dict((country, list_of_lists[idx]) for idx, country in enumerate(country_list))
Upvotes: 0