所以我有一个包含单词和数字的嵌套列表,如下例所示:
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循环遍历列表,但我希望有更好的方法。
答案 0 :(得分: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]]
使用dict(只需要单次迭代):
>>> 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
以提高效率。
答案 1 :(得分: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]]