Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python循环遍历列中的行并对它们进行计数?_Python_Loops_Count - Fatal编程技术网

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

如何使用Python循环遍历列中的行并对它们进行计数?,python,loops,count,Python,Loops,Count,我试图使用Python循环访问访问表中的列。我的列是按升序排序的 我试图在行中循环,当列中的值发生变化时,我想得到所有这些值的计数。在下面的示例列中,我要计算的第一组值是M1。当下一行变为M21时,我想计算M21,直到它变为M23b,依此类推 我不想使用if/else语句,因为有几百个不同的可能值。我在itertools模块中使用了groupby函数,但在我的示例中无法解决语法问题。我还尝试了一个愚蠢的循环,比如if row!=row.next():做点什么,但那件事在我脸上爆炸了。如果有人能为

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

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

我不想使用
if
/
else
语句,因为有几百个不同的可能值。我在
itertools
模块中使用了
groupby
函数,但在我的示例中无法解决语法问题。我还尝试了一个愚蠢的循环,比如
if row!=row.next():做点什么
,但那件事在我脸上爆炸了。如果有人能为我推荐一个解决方案或给我看一个示例脚本,我将不胜感激

示例列:

M1 M1 M1 M21 M21 M23b M23b S2 S23b S23B O1 O2 O2 O2 M1 M1 M1 M21 M21 M23b M23b S2 S23b S23B O1 氧气 氧气 氧气 你的直觉是正确的:

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
或者,如果您所需要的只是计数,那么简单如下:

from collections import Counter # Python 2.7+

group_counts = Counter(column)
您可以实现为:


在较旧版本的Python上。

如果要在循环中添加打印以执行其他工作,以下内容可能会有所帮助:

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()
    ...

您确定这些行不是迭代对象吗?迭代在循环中自然终止。嘿,谢谢agf!这为我指明了正确的方向。请看下面的评论。谢谢Ethan。在你和agf之间,我编写了一个脚本,几乎对我有用。
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()
    ...