我有一个包含字符串和整数的混合列表,我需要得到每个字符串之间数字的总和。理想情况下,最终结果将是一个元组列表,因为每个字符串和后面的数字属于一起(因此顺序很重要)。
我可以使用迭代提取数字,isinstance
但实际列表非常大,有时我每个字符串有 1 或 2 个数字。
my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]
ideal_output = [('a', 3) ('b', 3), ('h', 54), ('d', 4), (v, 27)]
这是使用itertools.groupby的解决方案:
my_list = ['a', 2, 1, 'b', 3, 'h', 50, 4, 'd', 4, 'v', 20, 7]
from itertools import groupby
groups = groupby(my_list, key=type) # group-by the type of the value
result = []
for key, group in groups:
string = next(group) # get the string first, we'll skip over it otherwise
if key is str:
_, values = next(groups) # move the generator forward to get to the numbers
result.append((string, sum(values))) # sum up the numbers
print(result)
输出:
[('a', 3), ('b', 3), ('h', 54), ('d', 4), ('v', 27)]
它确实假设字符串之间至少有一个数字。如果不是,您可以检查len
的g
,如果它大于 1,则为第一个值的值添加 0g
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句