相关疑难解决方法(0)

Python:如何获取列表中项目的排序数量?

在Python中,我有一个项目列表,如:

mylist = [a, a, a, a, b, b, b, d, d, d, c, c, e]
Run Code Online (Sandbox Code Playgroud)

我想输出如下内容:

a (4)
b (3)
d (3)
c (2)
e (1)
Run Code Online (Sandbox Code Playgroud)

如何输出列表中项目的计数和排行榜?我不太关心效率,只是任何方式工作:)

谢谢!

python

9
推荐指数
3
解决办法
9536
查看次数

Pyparsing - 令牌不可预测的顺序

我希望能够从一段文字中提取字母的类型和数量,其中字母可以是任何顺序.还有一些其他的解析正在进行中,但这一点让我难过!

input -> result
"abc" -> [['a',1], ['b',1],['c',1]]
"bbbc" -> [['b',3],['c',1]]
"cccaa" -> [['a',2],['c',3]]
Run Code Online (Sandbox Code Playgroud)

我可以使用搜索或扫描并重复每个可能的字母,但有一个干净的方式吗?

这是我得到的:

from pyparsing import *


def handleStuff(string, location, tokens):

        return [tokens[0][0], len(tokens[0])]


stype = Word("abc").setParseAction(handleStuff)
section =  ZeroOrMore(stype("stype"))


print section.parseString("abc").dump()
print section.parseString("aabcc").dump()
print section.parseString("bbaaa").dump()
Run Code Online (Sandbox Code Playgroud)

python pyparsing

7
推荐指数
2
解决办法
941
查看次数

标签 统计

python ×2

pyparsing ×1