【发布时间】:2020-07-06 23:08:16
【问题描述】:
我有一些函数可以检索项目列表,itens 矩阵。 检索矩阵后,我需要将元素放入一个新列表中,并避免重复。 使用嵌套的 for 循环很容易,但我想知道如何使用列表理解执行相同的操作。 我的问题是设置条件以避免插入重复的条件: 像这样:
伪代码:
new= [['Captain Marvel', 'Avengers: Infinity War', 'Ant-Man And The Wasp', 'The Fate Of The Furious', 'Deadpool 2'], ['Inhumans', 'The Fate Of The Furious', 'Venom', 'American Assassin', 'Black Panther']]
lista2 =[]
for movieL in new:
lista2 = [val
for sublist in new
for val in sublist
#if val not in lista2 this does not work
]
结果:
['Captain Marvel', 'Avengers: Infinity War', 'Ant-Man And The Wasp', 'The Fate Of The Furious', 'Deadpool 2', 'Inhumans', 'The Fate Of The Furious', 'Venom', 'American Assassin', 'Black Panther']
【问题讨论】:
-
为什么不直接使用
set:{val for sublist in new for val in sublist}? -
我不知道。谢谢,真的很容易。
标签: python list-comprehension unique nested-loops