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

2024-10-16 17:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个清单:

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

但我真的不知道如何在一个完整的迭代中,以一种快速而优雅的方式完成这项工作,如果可能的话。你知道吗


Tags: infor方式item字符次数mylistsetdefault
3条回答

如果要在一个通道中计算流入和流出,可以使用以下结构:

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})

注意,对于^{},您不需要setdefault。你知道吗

我使用itertools.groupby消除相同的连续项,然后计算流入转换。对于流出,我们只需将列表最后一项的流入计数减去1。你知道吗

from itertools import groupby
from collections import Counter

myList = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'b', 'a']

uniques = [key for key, g in groupby(myList)]  # ['a', 'b', 'a', 'c', 'b', 'a']
c = Counter(uniques)
inflow = dict(c)
c.update({myList[-1]: -1})  # No outflow for the last element
outflow = dict(c)

print(inflow)
# {'a': 3, 'b': 2, 'c': 1}

print(outflow)
# {'a': 2, 'b': 2, 'c': 1}

使用collections.Counteritertools.groupby

from collections import Counter
from itertools import groupby

def in_out_flow(lst):
    in_flow = Counter(lst)
    out_flow = Counter(k for k, _ in groupby(lst))
    out_flow[lst[-1]] -= 1
    for k,v in in_flow.items():
      print('key: {}, in flow: {}, out flow: {}'.format(k, v, out_flow[k]))

示例:

in_out_flow(['a', 'a', 'a', 'b', 'b', 'a', 'c', 'c', 'b', 'a'])
print('##')
in_out_flow(['a', 'a', 'a', 'b', 'a', 'c', 'a', 'b'])

输出:

key: a, in flow: 5, out flow: 2
key: b, in flow: 3, out flow: 2
key: c, in flow: 2, out flow: 1
##
key: a, in flow: 5, out flow: 3
key: b, in flow: 2, out flow: 1
key: c, in flow: 1, out flow: 1

相关问题 更多 >