在 for 循环中用 if 语句编写一行代码

One line coding with if statement inside for loop

我需要帮助将以下代码缩短为一行。

for i in objects:
    if i not in uniq: 
        uniq.append(i)

我只是为了挑战而做,不会保留这个。

最简单的 oneliner 是使用 set:

uniq = set(objects)

如果你真的需要一个列表,你当然可以从集合中创建一个:

uniq = list(set(objects))
objects= [9,9,1,2,3,4,5,5,9,9,15,12,33]    
uniq=[ele for i,ele in enumerate(objects) if objects.index(ele)==i]

产出

[9, 1, 2, 3, 4, 5, 15, 12, 33]

您可以使用列表理解,尽管出于多种原因这不是一个好主意

uniq=[]
objects= [9,9,1,2,3,4,5,5,9,9,15,12,33]
[uniq.append(i) for i in objects if i not in uniq]
print(uniq)

输出:

[9, 1, 2, 3, 4, 5, 15, 12, 33]

首先,从 style/readability 的角度来看,它读起来很混乱,'implicit rather than explicit' 除了将所有内容都放在一行上没有任何实际好处外,它没有为您的 FOR 循环增加任何价值。

其次,它很难修改,它仅限于一个操作,现在可能可以,但如果你需要添加第二个操作,你必须重构整个东西