gpt4 book ai didi

python - 如何获取列表中每个项目的流入/流出?

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:05 25 4
gpt4 key购买 nike

我有这个列表:

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

但我真的不知道如何以快速而优雅的方式为流出执行此操作,如果可能的话,在单个整体迭代中。

最佳答案

如果你想一次计算流入和流出,你可以使用这个结构:

from collections import Counter

last_char = None

my_list = "aaabbaccba"

inflow = Counter()
outflow = Counter()

for char in my_list:
inflow[char] += 1
if last_char and char != last_char:
outflow[last_char] += 1
last_char = char


print(inflow)
print(outflow)

输出:

Counter({'a': 5, 'b': 3, 'c': 2})
Counter({'a': 2, 'b': 2, 'c': 1})

请注意 Counter ,您不需要 setdefault

关于python - 如何获取列表中每个项目的流入/流出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com