如何将列表与其先前的条目相加,并用新的和更正的条目替代?

时间:2019-05-18 22:17:19

标签: python list graph sum iteration

我正在绘制公寓中的Internet连接图,并且有用于上传和下载速度以及时间的数据。我有所有这些变量的数据列表,但是我需要将自己的时间列表与其自身相加。也就是说,我需要[a,a + b,a + b + c,a + b + c + d,a + b + c + d + e,...]等。

我的带有时间的列表仅以10到20秒为间隔,我需要一种将它们加在一起并制成如图所示的列表的方法,有没有简单的方法呢?

我尝试用while循环进行迭代,但是没有运气。我没有知识提出聪明的主意,我是Python的新手。

iHaveThisList = ['a','b','c','d','e'] <-它们仍然被定义为字符串变量。

iNeedThisList = [a,a + b,a + b + c,a + b + c + d,a + b + c + d + e]

1 个答案:

答案 0 :(得分:1)

这项工作吗? (我认为效率不是最高)

    #Importing Modules
    from random import randint
    from pygame.locals import *
    import pygame
    ##################

    # Making User Controled Block
    class User_Block:
        def __init__(self):
          self.x_cor = 300
          self.y_cor = 300
          self.length = 20
          self.width = 20
          self.color = GREEN
          pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],0)
    ##############################

    # Making Enemys
    class Enemy_Block:
        def __init__(self):
          self.x_cor = randint(100,500)
          self.y_cor = 100
          self.length = randint(10,100)
          self.width = randint(10,100)
          self.color = (255,0,255)
          pygame.draw.rect(screen,self.color,[self.x_cor,self.y_cor,self.length,self.width],5)
    ########################

    # Set Up Screen
    screen = pygame.display.set_mode((600,600))
    ##########################################

    # Varible Used "while" Loop
    done = False
    #############


    # Colors
    WHITE = (0,0,0)
    BLACK = (255,255,255)
    RED = (255,0,0)
    GREEN = (0,255,0)
    BLUE = (0,0,255)
    ########################

    # User Controled Block
    User_Block = User_Block()
    ########################

    # Enemys
    Enemy_List = []
    for i in range(10):
      Enemy_List.append(Enemy_Block())
    ######################

    # Most important code here
    while not done:
        for event in pygame.event.get():
          if event.type == pygame.QUIT:
              done == True

          #Moving Character
          if event.type == pygame.KEYDOWN:
            if event.key == K_w:
              User_Block.y_cor += 100
        Clock = pygame.time.Clock()
        Clock.tick(60)
    ######################################

        pygame.display.update()
    pygame.quit()
    ###################

使用生成器更有效:

def cumsum(values):
    return [sum(values[:i]) for i in range(1, len(values))]