簡體   English   中英

如何遍歷列中的行並使用Python進行計數?

[英]How do I loop through the rows in a column and count them using Python?

我試圖使用Python遍歷訪問表中的列。 我的列升序排列。

我試圖遍歷行,並且當列中的值更改時,我想獲取所有這些值的計數。 在下面的示例列中,我要計算的第一組值是M1 當下一行更改為M21 ,我要對M21進行計數,直到它更改為M23b ,依此類推。

我不想使用if / else語句,因為有數百種可能的值。 我在itertools模塊中使用了groupby函數,但是在我的示例中無法itertools語法。 我還嘗試了一個愚蠢的循環,執行類似if row != row.next(): do_something但這使我的臉炸了。 如果有人可以提出解決方法或向我展示一個示例腳本來為我完成此工作,我將不勝感激。

示例列:

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

您使用itertools.groupby直覺是正確的:

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)

您可以將Counter實現為:

from collections import defaultdict:

group_counts = defaultdict(int)

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

在舊版本的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()
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM