简体   繁体   中英

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.

#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.

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. So you need to create the trainX outside of the loop, and then keep adding to it.

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:

# 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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