根据每个嵌套列表中的第二个元素从嵌套中对元素进行排序? [英] Sorting elements from a nested based on the second element in each nested list?

查看:290
本文介绍了根据每个嵌套列表中的第二个元素从嵌套中对元素进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我还有一个数字列表:

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.

我想输出为:

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

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

推荐答案

使用两个列表理解:

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

如果number_list很大,则先将其转换为set以提高效率.

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

这篇关于根据每个嵌套列表中的第二个元素从嵌套中对元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆