Python-在缺少索引的位置用零填充元组列表 [英] Python - filling a list of tuples with zeros in places of missing indexes
本文介绍了Python-在缺少索引的位置用零填充元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个元组列表:
[(0.0, 287999.70000000007),
(1.0, 161123.23000000001),
(2.0, 93724.140000000014),
(3.0, 60347.309999999983),
(4.0, 55687.239999999998),
(5.0, 29501.349999999999),
(6.0, 14993.920000000002),
(7.0, 14941.970000000001),
(8.0, 13066.229999999998),
(9.0, 10101.040000000001),
(10.0, 4151.6900000000005),
(11.0, 2998.8899999999999),
(12.0, 1548.9300000000001),
(15.0, 1595.54),
(16.0, 1435.98),
(17.0, 1383.01)]
可以看出,缺少索引(13和14).我想用零填充缺失的索引:
As can be seen, there are missing indexes (13 and 14). I want to fill the missing indexes with zeros:
[(0.0, 287999.70000000007),
(1.0, 161123.23000000001),
(2.0, 93724.140000000014),
(3.0, 60347.309999999983),
(4.0, 55687.239999999998),
(5.0, 29501.349999999999),
(6.0, 14993.920000000002),
(7.0, 14941.970000000001),
(8.0, 13066.229999999998),
(9.0, 10101.040000000001),
(10.0, 4151.6900000000005),
(11.0, 2998.8899999999999),
(12.0, 1548.9300000000001),
(13.0, 0),
(14.0, 0),
(15.0, 1595.54),
(16.0, 1435.98),
(17.0, 1383.01)]
我在 for循环
上做了一些丑陋的事情(我没有添加它,因为我认为它不会对任何事情有所贡献...),但是我想知道是否有任何优雅的方法可以解决这个问题?(也许使用 list comprehension
的3-4行).
I did something ugly with for loop
(I didn't add it cause I don't think it will contribute to anything...), but I was wondering is there any elegant way to resolve this problem? (maybe 3-4 lines with list comprehension
).
推荐答案
简单的 for
循环可能比列表理解更容易:
Just a straight for
loop is probably easier than a list comprehension:
data = [(0.0, 287999.70000000007),
(1.0, 161123.23000000001),
(2.0, 93724.140000000014),
(3.0, 60347.309999999983),
(4.0, 55687.239999999998),
(5.0, 29501.349999999999),
(6.0, 14993.920000000002),
(7.0, 14941.970000000001),
(8.0, 13066.229999999998),
(9.0, 10101.040000000001),
(10.0, 4151.6900000000005),
(11.0, 2998.8899999999999),
(12.0, 1548.9300000000001),
(15.0, 1595.54),
(16.0, 1435.98),
(17.0, 1383.01)]
result = []
last = 0.0
for d in data:
while last < d[0]:
result.append((last, 0))
last += 1
result.append(d)
last = d[0]+1
稍短(包括列表理解):
Slightly shorter (and including a list comprehension):
result, last = [], 0.0
for d in data:
result.extend((r,0) for r in range(int(last), int(d[0])))
result.append(d)
last = d[0]+1
这篇关于Python-在缺少索引的位置用零填充元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文