3

以下是我的清单:

col = [['red', 'yellow', 'blue', 'red', 'green', 'yellow'],
       ['pink', 'orange', 'brown', 'pink', 'brown']
      ]

我的目标是消除每个列表中出现一次的项目。

这是我的代码:

eliminate = [[w for w in c if c.count(w)>1]for c in col]

Output: [['red', 'red', 'yellow','yellow'], ['pink','pink', 'brown','brown']]

该代码适用于上述列表等小型数据集,但是,我的数据集非常大。每个列表最多包含 1000 个项目。

有没有办法让上面的代码工作得更快?就像将代码分解为两个或多个 for 循环一样,因为我的理解是正常的 for 循环比列表理解更快。

有什么建议么?谢谢。

4

4 回答 4

9

我会尝试OrderedCounter避免重复.count()调用:

from collections import OrderedDict, Counter

col=[['red', 'yellow', 'blue', 'red', 'green', 'yellow'],['pink', 'orange', 'brown', 'pink', 'brown']]

class OrderedCounter(Counter, OrderedDict):
    pass

new = [[k for k, v in OrderedCounter(el).iteritems() if v != 1] for el in col]
# [['red', 'yellow'], ['pink', 'brown']]

如果我们只想迭代一次,那么(类似于 Martijn 的 - 加上少玩集合):

from itertools import count
def unique_plurals(iterable):
    seen = {}
    return [el for el in iterable if next(seen.setdefault(el, count())) == 1]

new = map(unique_plurals, col)

这在指定需要出现的次数方面更加灵活,并且保留一个dict而不是多个sets。

于 2013-10-09T13:29:26.723 回答
7

不要使用.count(),因为它会扫描每个元素的列表。此外,如果它们在输入中出现 3 次或更多次,它会将项目多次添加到输出中。

你最好在这里使用一个生成器函数,它只产生它以前见过的项目,但只产生一次:

def unique_plurals(lst):
    seen, seen_twice = set(), set()
    seen_add, seen_twice_add = seen.add, seen_twice.add
    for item in lst:
        if item in seen and item not in seen_twice:
            seen_twice_add(item)
            yield item
            continue
        seen_add(item)

[list(unique_plurals(c)) for c in col]

这仅在每个列表中迭代一次(与使用 a 不同Counter())。

这种方法要快得多

>>> timeit('[[k for k, v in OrderedCounter(el).iteritems() if v != 1] for el in col]', 'from __main__ import col, OrderedCounter')
52.00807499885559
>>> timeit('[[k for k, v in Counter(el).iteritems() if v != 1] for el in col]', 'from __main__ import col, Counter')
15.766052007675171
>>> timeit('[list(unique_plurals(c)) for c in col]', 'from __main__ import col, unique_plurals')
6.946599006652832
>>> timeit('[list(unique_plurals_dict(c)) for c in col]', 'from __main__ import col, unique_plurals_dict')
6.557853937149048

这比方法快了大约 8 倍,是OrderedCounter方法的 2.2 倍Counter

不过,Jon 的单字典加计数器方法更快!

但是,如果您只需要消除仅出现一次的值,但保持其余部分(包括重复)完整,那么您可以使用(借用 Jon):

from itertools import count
from collections import defaultdict

def nonunique_plurals(lst):
    seen = defaultdict(count)
    for item in lst:
        cnt = next(seen[item])
        if cnt:
            if cnt == 1:
                # yield twice to make up for skipped first item
                yield item
            yield item

这会产生:

>>> [list(nonunique_plurals(c)) for c in col]
[['red', 'red', 'yellow', 'yellow'], ['pink', 'pink', 'brown', 'brown']]
>>> timeit('[non_uniques(c) for c in col]', 'from __main__ import col, non_uniques')
17.75499200820923
>>> timeit('[list(nonunique_plurals(c)) for c in col]', 'from __main__ import col, unique_plurals')
9.306739091873169

这几乎是 FMc 提出Counter()的解决方案速度的两倍,但它并没有准确地保留顺序:

>>> list(nonunique_plurals(['a', 'a', 'b', 'a', 'b', 'c']))
['a', 'a', 'a', 'b', 'b']
>>> non_uniques(['a', 'a', 'b', 'a', 'b', 'c'])
['a', 'a', 'b', 'a', 'b']
于 2013-10-09T13:31:49.087 回答
2

我的理解是,普通的 for 循环比列表理解要快。

没有。

您的循环很慢,因为它重复了操作。对于每个嵌套列表中的每个字符串,col它都会计算该字符串的实例数,因此对于每个cin col,它都会进行len(c)**2比较。那是O(NM^2)平方算法。这很快就会变慢。

为了加快速度,请使用更好的数据结构。使用collections.Counter.

于 2013-10-09T13:29:07.480 回答
1

这解决了您修改后的问题:它确实对内部列表进行了两次传递(首先计数,然后检索),因此不是尽可能快;但是,它保留了顺序并且非常易读。像往常一样,权衡比比皆是!

from collections import Counter

cols = [
    ['red', 'yellow', 'blue', 'red', 'green', 'yellow'],
    ['pink', 'orange', 'brown', 'pink', 'brown'],
]

def non_uniques(vals):
    counts = Counter(vals)
    return [v for v in vals if counts[v] > 1]

non_uniqs = map(non_uniques, cols)

# [
#    ['red', 'yellow', 'red', 'yellow'],
#    ['pink', 'brown', 'pink', 'brown'],
# ]
于 2013-10-09T14:11:00.237 回答