I have two variables:
unique_val = [1,2,3]
nested_list = [['name1',1],['name2',1],['name3',3],['name4',2],['name5',2],['name6',3]]
Basically I want separate lists of the names at each unique value. I struggled to put together a set of nested for loops to no avail.
Ideally the output would be something like this:
list_1 = ['name1','name2']
list_2 = ['name4','name5']
list_3 = ['name3',name6']
Creating variables for each item in unique_val
is not a good idea. Instead of hard coding everything better use a dict with keys like list_1
as it'll handle any number number of variables.
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> nested_list = [['name1',1],['name2',1],['name3',3],['name4',2],['name5',2],['name6',3]]
>>> unique_val = [1,2,3] #better make this a set to get O(1) lookup
>>> for v,k in nested_list:
if k in unique_val:
dic['list_'+str(k)].append(v)
#now access those lists:
>>> dic['list_1']
['name1', 'name2']
>>> dic['list_2']
['name4', 'name5']
>>> dic['list_3']
['name3', 'name6']
In case you had a 4 in unique_val
then you may expect list_4
to be an empty list, this is easily handled by a defaultdict
:
>>> dic['list_4']
[]
you can use list comprehension:
[[name for name, number in nested_list if number == n] for n in unique_val]
if you really want to put it in separate variable, you can do the following.
list_1, list_2, list_3 = [[name for name, number in nested_list if number == n] for n in unique_val]
来源:https://stackoverflow.com/questions/16862090/how-to-sort-nested-lists-into-seperate-lists-with-unique-values-in-python