【发布时间】:2022-01-13 02:57:22
【问题描述】:
我有一个列表列表,我想使用 for 循环对其进行迭代,并创建一个仅包含唯一单词的新列表。这类似于question asked previously,但我无法为列表中的列表
找到适合我的解决方案例如嵌套列表如下:
ListofList = [['is', 'and', 'is'], ['so', 'he', 'his'], ['his', 'run']],
所需的输出将是一个列表:
List_Unique = [['is','and','so','he','his','run']]
我尝试了以下两种代码变体,但它们的输出都是重复列表:
unique_redundant = []
for i in redundant_search:
redundant_i = [j for j in i if not i in unique_redundant]
unique_redundant.append(redundant_i)
unique_redundant
unique_redundant = []
for list in redundant_search:
for j in list:
redundant_j = [i for i in j if not i in unique_redundant]
unique_redundant.append(length_j)
unique_redundant
上述两个(不正确)变体的示例输出
(我在我的真实数据集上运行了代码,它在同一对单词的列表中给出了重复列表,尽管这不是实际的两个单词,只是一个示例):
List_Unique = [['is','and'],['is','and'],['is','and']]
【问题讨论】:
-
你想要嵌套列表输出还是单个列表?
-
我需要一个列表。因此,唯一搜索是在所有嵌套列表中查找唯一值,而不仅仅是在每个列表中
-
好的,下面有答案,看看吧