Skip to content Skip to sidebar Skip to footer

Sorting Elements From A Nested Based On The Second Element In Each Nested List?

So I have a nested list that contains words and numbers like the following example: nested_list = [['This', 1],['is' , 2],['a', 3],['list', 4]] I also have a list of numbers: numb

Solution 1:

Using two list comprehensions:

>>> nested_list = [['This', 1],['is' , 2],['a', 3],['list', 4]]
>>> number_list = [2,3]
>>> list1 = [item for item in nested_list if item[1] in number_list]
>>> list2 = [item for item in nested_list if item[1] not in number_list]
>>> list1
[['is', 2], ['a', 3]]
>>> list2
[['This', 1], ['list', 4]]

Using a dict( only single iteration is required):

>>> dic = {'list1':[], 'list2':[]}
for item in nested_list:
    if item[1] in number_list:
        dic['list1'].append(item)
    else:
        dic['list2'].append(item)
...         
>>> dic['list1']
[['is', 2], ['a', 3]]
>>> dic['list2']
[['This', 1], ['list', 4]]

If number_list is huge then convert it to a set first to improve efficiency.


Solution 2:

You can use filter:

In [11]: filter(lambda x: x[1] in number_list, nested_list)
Out[11]: [['is', 2], ['a', 3], ['list', 3]]

In [12]: filter(lambda x: x[1] not in number_list, nested_list)
Out[12]: [['This', 1]]

Post a Comment for "Sorting Elements From A Nested Based On The Second Element In Each Nested List?"