Python 根据每个嵌套列表中的第二个元素对嵌套列表中的元素进行排序?

Python 根据每个嵌套列表中的第二个元素对嵌套列表中的元素进行排序?,python,sorting,nested-lists,Python,Sorting,Nested Lists,因此,我有一个嵌套列表,其中包含单词和数字,如以下示例所示: nested_list = [['This', 1],['is' , 2],['a', 3],['list', 4]] 我还有一个数字列表: number_list = [2,3] 我想根据天气情况生成两个嵌套列表,列表的第二个元素包含数字列表中的一个数字 我希望输出为: list1 = [['is', 2],['a', 3]] #list one has values that matched the number_list l

因此,我有一个嵌套列表,其中包含单词和数字,如以下示例所示:

nested_list = [['This', 1],['is' , 2],['a', 3],['list', 4]]
我还有一个数字列表:

number_list = [2,3]
我想根据天气情况生成两个嵌套列表,列表的第二个元素包含数字列表中的一个数字

我希望输出为:

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
我使用for循环遍历列表,但我希望有更好的方法。

您可以使用:


使用两种列表理解:

>>> 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]]
使用dict(只需要一次迭代):


如果
number\u列表
很大,则首先将其转换为
集合
,以提高效率。

请发布您尝试过的内容…与列表不匹配吗?是的。。。我想我解决了这个问题。对不起,你不是已经问过这个问题了吗?不过,请列出更多的蟒蛇!
>>> 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]]
>>> 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]]