如何在Python中使用列表推导减少行?

时间:2013-07-19 09:29:57

标签: python list

我有一些语法:

l_one = [ x for x in someList ] # list with duplicates
l = []
l_two = [ l.append( y ) for y in l_one if y not in l ] # duplicates removed

l和l_two都是相同的列表,没有重复。有没有办法减少线条,也许有oneliner?

编辑: 更正 - l_two是“非限制”列表。

2 个答案:

答案 0 :(得分:3)

实际上,它们并不相同。 .append()会返回None,因为它会修改列表,因此l_two是一个包含None个字符串的列表。但是,l将是没有欺骗的列表。

如果要从列表中删除重复项,可以将其设置为一个集合:

l_two = list(set(l_one))

请注意,这会删除订单。


如果要使用不可用的类型,请尝试使用for循环而不是列表解析:

l_one = [x for x in someList]
l_two = []
for i in l_one:
    if i not in l_two:
        l_two.append(i)

或者:

from itertools import groupby
l_two = [key for key, value in groupby(l_one)]

答案 1 :(得分:1)

如果我理解正确的话,你会从一个名为someList的列表开始,它可能有重复项,你想最终得到相同的列表,但删除了重复项?

您可以从删除第一行代码开始,这只是将someList复制到一个名为l_one的新(但相同)列表中:

>>> someList = [ 3,1,4,1,5,9,2,7 ]
>>> l = []
>>> [ l.append(y) for y in someList if y not in l]
[None, None, None, None, None, None, None]
>>> print l
[3, 1, 4, 5, 9, 2, 7]
>>>

即使someList的元素本身就是列表,这也有效:

>>> l = []
>>> someList = [[1,2],[2,1],[1,2],[3,4]]
>>> l = []
>>> [ l.append(y) for y in someList if y not in l]
[None, None, None]
>>> print l
[[1, 2], [2, 1], [3, 4]]
>>>