Sorting elements from a nested based on the second element in each nested list? [duplicate]

非 Y 不嫁゛ 提交于 2019-12-13 07:52:36

问题


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:

number_list = [2,3]

I want to generate a two nested lists based on weather the second element of the list contains a number in the list of numbers.

I want to output to be:

list1 = [['is', 2],['a', 3]] #list one has values that matched the number_list
list2 = [['This', 1],['list', 4]] #list two has values that didn't match the number_list

I was using a for loop to iterate through the list but I was hoping that there was a better way.


回答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.




回答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]]


来源:https://stackoverflow.com/questions/17117392/sorting-elements-from-a-nested-based-on-the-second-element-in-each-nested-list

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