I have two variables:
unique_val = [1,2,3]
nested_list = [[\'name1\',1],[\'name2\',1],[\'name3\',3],[\'name4\',2],[\'name5\',2],[\'name6\',3]]
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]
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']
[]