Skip to main content
 首页 » 编程设计

python之根据我的代码多行到单行

2025年05月04日18sharpest

有很多例子,但我找不到合适的例子来解决我的目标。

a = [["I", "have", "something"], ["she", "has", "nothing", "but", "something"]] 
 
temp = [] 
for i in range(len(a)): 
    for word in a[i]: 
        if word not in temp: 
            temp.append(word) 

我的尝试:

temp = [word for i in range(len(a)) for word in a[i] if word not in temp] 

无论如何要将它转换为单行? 有没有更短或更聪明的方法来降低时间复杂度? 顺便说一句,请不要使用库,因为我将在中文单词上使用它。

请您参考如下方法:

在一行(或两行)中并将时间复杂度降低到 O(n):

from collections import OrderedDict 
 
a = [["I", "have", "something"], ["she", "has", "nothing", "but", "something"]] 
r = list(OrderedDict.fromkeys(k for e in a for k in e)) 
print(r) 

输出

['I', 'have', 'something', 'she', 'has', 'nothing', 'but'] 

请注意,此版本将保持元素的顺序并适用于多个 Python 版本。