如何通过一个字典的值迭代,直到没有更多的值(达到字典的结束)?



假设我有一个字典,比如

d = {'Item 1': [3,4,5,3], 'Item 2': [2,3,4], 'Item 3': [5,34,75,35,65]}

我要做的是计算列表中两个元素的总和,并将它们相加。例如对于Item 1,我想要执行3 + 4,4 + 5,5 + 3,并在到达字典的最后一个值时停止。类似地,我想对字典中的所有值执行此操作,并将它们加到一个总数中。

如果你有Python 3.10,你可以使用itertools.pairwise:

from itertools import pairwise, chain
d = {
'Item 1': [3,4,5,3],
'Item 2': [2,3,4],
'Item 3': [5,34,75,35,65]
}
for key, numbers in d.items():
s = sum(chain.from_iterable(pairwise(numbers)))
print(f"{key}: {s}")

输出:

Item 1: 24
Item 2: 12
Item 3: 358

或者,如果你没有Python 3.10,你可以定义你自己的pairwise:

from itertools import tee, chain
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
yield from zip(a, b)

如果你只想要一个总金额:

total_sum = sum(sum(chain.from_iterable(pairwise(nums))) for nums in d.values())

您可以使用for循环遍历字典,就像您使用list, iterable, tuple或set一样:

for item in d:
print(item)

将字典中每个列表中的成对项相加则更为复杂。你必须求出列表的长度,我不知道怎么做。但是,如果您只想将每个列表中的所有项加起来(以便[2, 7, 1]变成10),您可以这样做。使用问题中的字典:

d = {
'Item 1': [3,4,5,3],
'Item 2': [2,3,4],
'Item 3': [5,34,75,35,65]
}
sums = [] # blank list
for list in d:
n = 0 # used as a local variable
for item in list:
n += item
sums.append(n) # put n on the end of sums
print(sums)

注意这里是而不是在列表中添加相邻的对,相反,它打印一个包含d中列表和的列表。我希望我的回答能帮到你。

相关内容

最新更新