识别列表中连续重复项的最 Pythonic 方法是什么?

发布于 2024-11-15 11:45:37 字数 743 浏览 2 评论 0原文

我有一个整数列表,我希望能够识别连续的重复块:也就是说,我想生成一个保序的双组列表,其中每个双组包含(int_in_question,出现次数)。

例如,如果我有一个如下列表:

[0, 0, 0, 3, 3, 2, 5, 2, 6, 6]

我希望结果是:

[(0, 3), (3, 2), (2, 1), (5, 1), (2, 1), (6, 2)]

我有一个相当简单的方法来使用 for 循环、临时变量和计数器来实现此目的:

result_list = []
current = source_list[0]
count = 0
for value in source_list:
    if value == current:
        count += 1
    else:
        result_list.append((current, count))
        current = value
        count = 1
result_list.append((current, count))

但我真的很喜欢python 的函数式编程习惯,我希望能够使用一个简单的生成器表达式来完成此操作。然而,我发现在使用生成器时很难保持子计数。我有一种感觉,两步过程可能会让我到达那里,但现在我被难住了。

有没有一种特别优雅/Pythonic 的方法来做到这一点,特别是对于生成器?

I've got a list of integers and I want to be able to identify contiguous blocks of duplicates: that is, I want to produce an order-preserving list of duples where each duples contains (int_in_question, number of occurrences).

For example, if I have a list like:

[0, 0, 0, 3, 3, 2, 5, 2, 6, 6]

I want the result to be:

[(0, 3), (3, 2), (2, 1), (5, 1), (2, 1), (6, 2)]

I have a fairly simple way of doing this with a for-loop, a temp, and a counter:

result_list = []
current = source_list[0]
count = 0
for value in source_list:
    if value == current:
        count += 1
    else:
        result_list.append((current, count))
        current = value
        count = 1
result_list.append((current, count))

But I really like python's functional programming idioms, and I'd like to be able to do this with a simple generator expression. However I find it difficult to keep sub-counts when working with generators. I have a feeling a two-step process might get me there, but for now I'm stumped.

Is there a particularly elegant/pythonic way to do this, especially with generators?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谜兔 2024-11-22 11:45:37
>>> from itertools import groupby
>>> L = [0, 0, 0, 3, 3, 2, 5, 2, 6, 6]
>>> grouped_L = [(k, sum(1 for i in g)) for k,g in groupby(L)]
>>> # Or (k, len(list(g))), but that creates an intermediate list
>>> grouped_L
[(0, 3), (3, 2), (2, 1), (5, 1), (2, 1), (6, 2)]

正如他们所说,包含电池

使用 JBernardo 的 sum 和生成器表达式的建议;见评论。

>>> from itertools import groupby
>>> L = [0, 0, 0, 3, 3, 2, 5, 2, 6, 6]
>>> grouped_L = [(k, sum(1 for i in g)) for k,g in groupby(L)]
>>> # Or (k, len(list(g))), but that creates an intermediate list
>>> grouped_L
[(0, 3), (3, 2), (2, 1), (5, 1), (2, 1), (6, 2)]

Batteries included, as they say.

Suggestion for using sum and generator expression from JBernardo; see comment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文