如何使用 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
I am trying to loop through column in an access table using Python. The column I have is sorted ascending.
I am trying to loop though the rows and when the value in the column changes, I want to get count of of all those values. In the example column below, the first group of values I want to count are the M1
's. When the next row changes to M21
, I want to count the M21
's until it changes to M23b
and so on.
I don't want to use an if
/else
statement, because there are a few hundred different possible values. I played around with the groupby
function in the itertools
module, but I haven't been able to solve the syntax to work in my example. I also tried a silly loop doing something like if row != row.next(): do_something
but that blew up in my face. If anyone can suggest a work-around or show me a sample script that will do this for me, I'd appreciate it.
Example Column:
M1 M1 M1 M21 M21 M23b M23b S2 S23b S23B O1 O2 O2 O2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用
itertools.groupby
的直觉是正确:或者,如果您需要的只是计数,则很简单:
您可以实现
Counter
as:在旧版本的 Python 上。
Your intuition to use
itertools.groupby
was correct:Alternatively, if all you need is the counts, it's as simple as:
You can implement
Counter
as:on older versions of Python.
如果您想在执行其他工作的循环中添加打印,以下内容可能会有所帮助:
If you want to add printing in a loop doing other work, the following may be helpful: