Python-将值追加到列表中

问题描述 投票:0回答:1

在下面的代码中,每个x具有y的9个值。我想要new_gamesplyed = [x,y1,y2,y3,y4,y5,y6,y7,y8,y9]。但是在“差异”列表中,所有292个值都被立即存储。

new_gamesplayed = []
difference = []

col_count = df_gamesplayed.shape[1]-1 = 9
l = len(df_gamesplayed) = 292

for x in range(len(df_gamesplayed)):      
    for y in range (1, col_count):
        diff = abs(df_gamesplayed.iloc[x, y] - df_gamesplayed.iloc[x, y + 1])        
        difference.append(diff)
    new_gamesplayed.append([df_gamesplayed.iloc[x, 0], difference])    
python list for-loop append
1个回答
0
投票

您正在整个代码段中使用相同的difference变量,因此也就不足为奇了,它存储了append传递给它的所有值。>

如果我正确理解,则需要在主循环中的某些语句之间“重置”容器。因此,我建议每次在主循环语句开始时重新初始化存储桶集合。示例:

for x in range(len(df_gamesplayed)):      
    d_temp = []  # <---------  reset it here ----------
    for y in range (1, col_count):
        diff = abs(df_gamesplayed.iloc[x, y] - df_gamesplayed.iloc[x, y + 1])        
        d_temp.append(diff)
    new_gamesplayed.append([df_gamesplayed.iloc[x, 0], d_temp])
© www.soinside.com 2019 - 2024. All rights reserved.