我有这个清单:
myList = [a, a, a, b, b, a, c, c, b, a]
我要计算每一项的流入量和流出量。你知道吗
‘a’的流入量=出现次数=5 (当过渡进入“a”时)
“a”的流出量=在“a”之后的不同字符数=2 (当从“a”到另一个字符的转换退出时)
对于我来说,我有这个,它是有效的:
myListDict = {}
for item in myList:
myListDict.setdefault(item, 0)
myListDict[item] += 1
但我真的不知道如何在一个完整的迭代中,以一种快速而优雅的方式完成这项工作,如果可能的话。你知道吗
如果要在一个通道中计算流入和流出,可以使用以下结构:
它输出:
注意,对于^{} ,您不需要
setdefault
。你知道吗我使用
itertools.groupby
消除相同的连续项,然后计算流入转换。对于流出,我们只需将列表最后一项的流入计数减去1。你知道吗使用
collections.Counter
和itertools.groupby
:示例:
输出:
相关问题 更多 >
编程相关推荐