How to sort nested lists into seperate lists with unique values in python?

a 夏天 提交于 2019-12-02 05:06:47

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!