遍历列表以指定顺序获取值

时间:2020-02-19 22:20:45

标签: python python-3.x list numpy tuples

我有一个初始元组,我试图对其进行迭代以执行进一步的计算。但是,我最终遇到了错误“ too many values to unpack”,该错误可以通过遵循先前提出的该问题的建议来解决(Python - too many values to unpack)。但是,现在将其转换为列表后,出现另一个错误'list' object has no attribute 'reshape'

我的代码如下:

Z=[([A,3],[A1,6])]  #A and A1 are 2x2 matrices 
y=[]
for data,label in Z:

    x = data.reshape((4,))
    y.append(int(label))

我可以理解错误原因。在这种情况下,我希望循环运行两次(因为我有两组数据[A-3,A1-6]),而data, label为:A3A16。但是它被误读为data = [A,3]label = [A1,6]

以这种方式循环遍历此列表并生成数据的正确方法是什么?

N.B:Z不必是列表,如果可以简化生活,我可以将其更改为元组。

1 个答案:

答案 0 :(得分:2)

元组在列表内。您只是遍历列表,而不遍历元组元素。您需要嵌套循环。

for t in Z:
    for data, label in t:
        x = data.reshape(4,)
        y.append(int(label))

如果您摆脱了列表,则不需要嵌套循环。

Z=([A,3],[A1,6])  #A and A1 are 2x2 matrices 
y=[]
for data,label in Z:
    x = data.reshape((4,))
    y.append(int(label))