如何在列中循环行并使用Python对它们进行计数?

2024-04-26 10:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python循环访问表中的列。我的列按升序排序。在

我试图遍历行,当列中的值发生变化时,我想得到所有这些值的计数。在下面的示例列中,我要计数的第一组值是M1。当下一行更改为M21时,我要对M21进行计数,直到它变为M23b,依此类推。在

我不想使用if/else语句,因为可能有几百个不同的值。我在itertools模块中反复使用了groupby函数,但是我还不能解决示例中的语法问题。我也尝试过一个愚蠢的循环来做类似if row != row.next(): do_something的事情,但那却在我脸上炸开了。如果有人能提出一个解决办法,或者给我看一个能帮我做到这一点的示例脚本,我将不胜感激。在

示例列:

M1
M1
M1
M21
M21
M23b
M23b
S2
S23b
S23B
O1
O2
O2
O2

Tags: 模块示例if排序语句elserow计数
2条回答

如果要在执行其他工作的循环中添加打印,请执行以下操作:

from collections import Counter  # or defaultdict

col_counts = Counter()           # or defaultdict(int)

last_value = object()            # won't show up in table
for row in access_table:
    col_counts[row[field]] += 1
    if row[field] != last_value:
        print(col_counts[last_value])
        last_value = row[field]
    ...
    other_processing()
    ...

你使用^{}的直觉是正确的:

for key, group in groupby(column):
    count = sum(1 for item in group) # Thanks JBernardo
    # the key is what is in the column, count is the number of items

或者,如果您只需要计数,则简单到:

^{pr2}$

您可以将^{}实现为:

from collections import defaultdict:

group_counts = defaultdict(int)

for item in column:
    group_counts[item] += 1

在Python的旧版本上。在

相关问题 更多 >