从另一个列表中向列表添加值

时间:2017-02-21 14:35:27

标签: python list elements

我设置了一系列' for'循环,现在可以确定3个值。我现在想要将3个值存储在列表中。这是我到目前为止所尝试的:

output = []                 # creates empty list
k = 0  
for i in range(len(GPS[0])-1):          # for loop through 1 column of GPS .csv this is the time
    for j in range(len(Data[0])-1):     # for loop through 1st column of Data .csv this is the time
        if GPS[1,i] == Data[1,j]:       # if loop, so if time in GPS = time in Data
              delta = i-j               # finds the difference between values
              #print(i,j, delta)          # prints row in i that matches row in j, and also the difference between them
              #print(GPS[1,i],Data[1,j])  # prints the Height from GPS and time from Data  
              output[k] = output.append(GPS[1,i], GPS[0,i], Data[1,j])
              k=k+1
print(output)

基本上我希望输出是包含3个值GPS[1,i]GPS[0,i]Data[0,j]的列表。我试图使用附加功能,但我似乎无法随身携带它,我得到的只是一个“没有”的列表

2 个答案:

答案 0 :(得分:0)

这是不对的:

output.extend

请改用output = [] # creates empty list k = 0 for i in range(len(GPS[0])-1): # for loop through 1 column of GPS .csv this is the time for j in range(len(Data[0])-1): # for loop through 1st column of Data .csv this is the time if GPS[1,i] == Data[1,j]: # if loop, so if time in GPS = time in Data delta = i-j # finds the difference between values #print(i,j, delta) # prints row in i that matches row in j, and also the difference between them #print(GPS[1,i],Data[1,j]) # prints the Height from GPS and time from Data output.extend([GPS[1,i], GPS[0,i], Data[1,j]]) k=k+1 print(output) 。所以你的代码可能如下所示:

output.append([GPS[1,i], GPS[0,i], Data[1,j]])

此外,如果你想在输出中附加一个元组,你可以改为>>> output = [] >>> output.extend([1,2,3]) >>> output [1, 2, 3]

Extend会添加要列出的元素

>>> output = []
>>> output.append([1,2,3])
>>> output
[[1, 2, 3]]

追加将创建一个新列表并将新列表添加到列表中

react-native-sound

答案 1 :(得分:0)

您无需使用output[k]append本身会将其添加到output。说实话,你甚至不需要k因为k等于output的长度。

append不能像你想要的那样接受多个参数。如果要将三位数据一起添加为元组,请使用:

output.append((GPS[1,i], GPS[0,i], Data[1,j]))

编辑:由于您只想将它​​们添加到列表中,请使用extend

output.extend([GPS[1,i], GPS[0,i], Data[1,j]])