[英]Adding values to a list, from another list
我设置了一系列“ 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]
。 我尝试使用append,但是似乎无法使用它,我得到的只是一个“无”列表
这是不对的:
output[k] = output.append(GPS[1,i], GPS[0,i], Data[1,j])
使用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]
追加将创建一个新列表并将新列表添加到您的列表
>>> output = []
>>> output.append([1,2,3])
>>> output
[[1, 2, 3]]
您不需要使用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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.