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

时间:2017-08-07 06:47:05

标签: python matplotlib

我知道如何在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)]]

我是Python的新手,但是我无法找到一种可以迭代的方式将trainX数组扩展到我想要的长度。

1 个答案:

答案 0 :(得分:0)

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

这会在每次迭代时覆盖trainX,所以最后你只会有两个元素。所以你需要在循环之外创建trainX,然后继续添加它。

请注意,如果您只是在每次迭代时添加一个元素,则不需要扩展。您可以保留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))