-1

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

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

4

2 回答 2

1

使用两个列表推导:

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

如果number_list很大,则将其转换为set第一个以提高效率。

于 2013-06-14T21:20:43.270 回答
0

您可以使用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]]
于 2013-06-14T21:19:46.477 回答