在python列表中插入第7个元素之后的前7个元素的总和

时间:2017-04-21 23:11:37

标签: python python-2.7

我想在第7个元素之后插入前7个元素的总和,在另外7个元素之后插入接下来的7个元素的总和,并且同样明智。

a1_tr = [21.1, 10.5, 6.31, 21.1, 6.31, 6.3, 10.4, 17.1, 7.61, 17.2, 7.6, 15.4, 8.54, 8.53, 21.1, 9.47, 7.01, 9.47, 7.01, 6.98, 21.1, 8.34, 16.7, 16.7, 8.34, 15.3, 8.28, 8.39, 9.83, 20.4, 6.77, 6.78, 21.8, 9.69, 6.78, 7.73, 16.7, 8.33, 8.34, 7.74, 16.7, 16.7, 8.2, 16.5, 8.23, 16.4, 8.18, 8.2, 16.5, 21.1, 21.1, 21.1, 21.1, 21.1, 21.1, 21.1]
len(a1_tr) = 56

我想在此列表中添加8个元素,使其长度为64。

这是元素列表,其中包含以上列表中7个元素的总和:

trsumlist = [82.02000000000001, 81.97999999999999, 82.13999999999999, 82.05, 82.05, 82.24, 82.21, 147.7]

以下是我的尝试:

i = 1
x = 0
>>> while i <= len(a1_tr):
     a1_tr.insert(i, trsumlist[x])
     x = x+1
     i += 8

>>> a1_tr
[21.1, 10.5, 6.31, 21.1, 6.31, 6.3, 10.4, 17.1, 7.61, 17.2, 7.6, 15.4, 8.54, 8.53, 21.1, 9.47, 7.01, 9.47, 7.01, 6.98, 21.1, 8.34, 16.7, 16.7, 8.34, 15.3, 8.28, 8.39, 9.83, 20.4, 6.77, 6.78, 21.8, 9.69, 6.78, 7.73, 16.7, 8.33, 8.34, 7.74, 16.7, 16.7, 8.2, 16.5, 8.23, 16.4, 8.18, 8.2, 16.5, 21.1, 21.1, 21.1, 21.1, 21.1, 21.1, 21.1]

>>> len(a1_tr)
56

这不是在第7个元素之后插入任何元素,有人可以建议我用其他方法来实现这个吗?

4 个答案:

答案 0 :(得分:0)

最明显的方法是迭代列表,并保持运行总计。然后,在每第七个元素之后添加总数。

a1_tr = [21.1, 10.5, 6.31, 21.1, 6.31, 6.3, 10.4, 17.1, 7.61, 17.2, 7.6, 15.4, 8.54, 8.53, 21.1, 9.47, 7.01, 9.47,
         7.01, 6.98, 21.1, 8.34, 16.7, 16.7, 8.34, 15.3, 8.28, 8.39, 9.83, 20.4, 6.77, 6.78, 21.8, 9.69, 6.78, 7.73,
         16.7, 8.33, 8.34, 7.74, 16.7, 16.7, 8.2, 16.5, 8.23, 16.4, 8.18, 8.2, 16.5, 21.1, 21.1, 21.1, 21.1, 21.1,
         21.1, 21.1]

idx = 0
sum_ = 0
new = list()
for element in a1_tr:
    idx += 1
    sum_ += element
    new.append(element)
    if idx == 7:
        new.append(sum_)
        sum_ = 0
        idx = 0

print(new)

更简洁:

a1_tr = [21.1, 10.5, 6.31, 21.1, 6.31, 6.3, 10.4, 17.1, 7.61, 17.2, 7.6, 15.4, 8.54, 8.53, 21.1, 9.47, 7.01, 9.47,
         7.01, 6.98, 21.1, 8.34, 16.7, 16.7, 8.34, 15.3, 8.28, 8.39, 9.83, 20.4, 6.77, 6.78, 21.8, 9.69, 6.78, 7.73,
         16.7, 8.33, 8.34, 7.74, 16.7, 16.7, 8.2, 16.5, 8.23, 16.4, 8.18, 8.2, 16.5, 21.1, 21.1, 21.1, 21.1, 21.1,
         21.1, 21.1]

n = 7
chunks = [a1_tr[idx:idx+n] + [sum(a1_tr[idx:idx+n])] for idx in range(0, len(a1_tr), n)]
new = [x for y in chunks for x in y]
print(new)

答案 1 :(得分:0)

您可以将这些项目分组为七人组,然后使用sumlambda添加到map中:

it = iter(a1_tr)
r = [i for x in map(lambda *x: x+(sum(x),), *[it]*7) for i in x] 
print(r)

或者使用更详细的itertools.groupby进行分组,然后获取每组的总和:

from itertools import groupby, count

c = count()
r = []
for _, g in groupby(a1_tr, lambda _: next(c)//7):
    g = list(g)
    g.append(sum(g))
    r.extend(g)
print(r)

答案 2 :(得分:0)

如何只使用一个列表理解?

Supporter

答案 3 :(得分:0)

这是另一种方法,使用isliceiter的组合

new = []
it = iter(a1_tr)
take = list(islice(it,7)) # take the first 7 elements
while take: #while there is something do
    new += take
    new.append( sum(take) )
    take = list(islice(it,7)) # take the next 7 elements
print(new)