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

后端 未结 2 794
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 14:05

I have two variables:

unique_val = [1,2,3]
nested_list = [[\'name1\',1],[\'name2\',1],[\'name3\',3],[\'name4\',2],[\'name5\',2],[\'name6\',3]]

相关标签:
2条回答
  • 2021-01-23 14:48

    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]
    
    0 讨论(0)
  • 2021-01-23 15:01

    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']
    []
    
    0 讨论(0)
提交回复
热议问题