python - 在 python 的列表列表中查找唯一的单词

我有一个列表列表,我想使用 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']]

最佳答案

我建议使用 set() class union()这样:

ListofList = [['is', 'and', 'is'], ['so', 'he', 'his'], ['his', 'run']]

set().union(*ListofList)
# => {'run', 'and', 'so', 'is', 'his', 'he'}

解释

它的工作原理如下:

test_set = set().union([1])
print(test_set)
# => {1}

列表前的星号运算符 (*ListofList) 解包列表:

lst = [[1], [2], [3]]
print(lst) #=> [[1], [2], [3]]
print(*lst) #=> [1] [2] [3]

https://stackoverflow.com/questions/70270242/

相关文章:

r - 缩短 R 中的长向量

c# - 如何在 C# 中创建 JSON 对象

maven - 如何找到 Log4j 的深层用法

c++ - 访问元组 vector 中的元素 C++

vue.js - 有没有可能把它变成 '<script setup>' ?我尝试了很多方法但可

r - 忽略 R 中某些值的行求和值

rust - 特征的静态工厂方法

next.js - 单击链接后如何关闭模态窗口

svelte - svelte.config.js 错误语法错误 : Cannot use impo

regex - 在 perl 中使用 foreach 代替 map 和 grep