简体   繁体   English

如何在python中连续向另一个添加列表

[英]How To Continuously Add lists to another in python

I know how to add arrays to each other in python but I am confused on how to continuously extend an array. 我知道如何在python中相互添加数组,但是我对如何连续扩展数组感到困惑。

#import numpy as np
import matplotlib.pyplot as plt
import xlrd

path = r"C:\Users\berro\Documents\Sample Excel and CSV Files\shoesize.xls"

book = xlrd.open_workbook(path)
#print(book.nsheets)
#print(book.sheet_names())

sheet = book.sheet_by_index(0)

print(sheet.row_values(1,2,4))


for x in range (1,11):
    trainX = [sheet.row_values(x,2,4)]
    trainX.extend([sheet.row_values(x+1,2,4)])

print(trainX)


trainX.append(sheet.row_values(2, 2, 4))
trainX.append(sheet.row_values(4,2,4))
trainX.append(sheet.row_values(5,2,4))
trainX.append(sheet.row_values(6,2,4))
trainX.append(sheet.row_values(7,2,4))
trainX.append(sheet.row_values(8,2,4))
trainX.append(sheet.row_values(9,2,4))
print(trainX)




#shoe size, height
features = [[sheet.row_values(1,2,4),sheet.row_values(2,2,4)]]

I'm some what new to Python, but I am having trouble finding an iterate-able way to extend the trainX array to my desired length. 我是Python的新手,但是我很难找到一种可迭代的方法来将trainX数组扩展到所需的长度。

for x in range (1,11):
    trainX = [sheet.row_values(x,2,4)]
    trainX.extend([sheet.row_values(x+1,2,4)])

This overwrites trainX on every iteration, so in the end you will only have two elements in there. trainX在每次迭代时覆盖trainX ,因此最后您将只有两个元素。 So you need to create the trainX outside of the loop, and then keep adding to it. 因此,您需要在循环外部创建trainX ,然后继续添加它。

Note that you do not need to extend if you are just adding a single element on each iteration. 请注意,如果仅在每次迭代中添加单个元素,则无需扩展 You can keep the append then: 您可以保留append

# create an empty list first
trainX = []

# start at index 1, end at index 9 (inclusive; or exclusive 10)
for x in range (1, 10):
    trainX.append(sheet.row_values(x, 2, 4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM