gpt4 book ai didi

python - 如何拆分列表中值的重复计数并显示实际值?

转载 作者:行者123 更新时间:2023-12-01 01:14:59 25 4
gpt4 key购买 nike

列表中的重复值显示为“99*0.00”,表示 0.00 值的 99 倍。我想将列表转换为数组并将这些重复计数显示为实际值。

我尝试构建一个 if 循环,但没有成功。

my_list = ['99*0.00', '24.93', '24.91', '24.92', '5*24.98','25.00', '305*1.00',
'25.04', '25.02', '24.94', '24.94', '24.94', '24.95']

最佳答案

您可以创建一个函数,将元素扩展为重复值列表

def expand(s):
if '*' in s:
repeat, value = s.split('*')
return [value for _ in range(int(repeat))]
else:
return [s]

然后在每个元素上调用此方法,并展平结果列表

import itertools
list(itertools.chain.from_iterable(expand(s) for s in my_list))

这会导致

['0.00', '0.00', '0.00', ..., '24.93', '24.91', '24.92', '24.98', '24.98', '24.98', '24.98', '24.98', '25.00', '1.00', '1.00', '1.00', ..., '25.04', '25.02', '24.94', '24.94', '24.94', '24.95']

关于python - 如何拆分列表中值的重复计数并显示实际值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54445301/

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