【问题标题】:TypeError when trying to print contents of a numpy array尝试打印 numpy 数组的内容时出现 TypeError
【发布时间】:2018-02-08 09:35:21
【问题描述】:

我尝试将数组从列表转换为数组:事实上,我在 9 组 tempTracesHW [hw] hw=[0,9] 中有滑动轨迹然后我只想显示每个 temTracesHW 中的一个元素,所以我转换tempTracesHW[i] 变成这样的表:

tempTraces = np.load(r'E:\\blockData\\Concatenated_Traces.npy')

print (tempTraces.shape)     
tempSbox = [inv_sbox[tempCText[i][0] ^ tempKey[i][0]] for i in range(len(tempCText))] 
tempHW   = [hw[s] for s in tempSbox]

tempTracesHW = [[] for _ in range(9)]
print tempTracesHW
        # Fill them up
for i in range(len(tempTraces)):
    HW = tempHW[i]
    tempTracesHW[HW].append(tempTraces[i])

# Switch to numpy arrays        
tempTracesHW = [np.array(tempTracesHW[HW]) for HW in range(9)]
print(tempTracesHW)

for i in range(HW):
    print('hw=',i)
    print(len(tempTracesHW[i]))
    print(tempTracesHW[i])
    Tab= np.asarray(tempTracesHW[i])
    print(Tab.shape)
    for k in len(Tab):
        print(Tab[k])

但它给了我这个错误:

    for k in len(Tab):

TypeError: 'int' object is not iterable

【问题讨论】:

  • 你需要从len返回的int创建一个iterable:for k in range(len(Tab)),prolly。

标签: python arrays for-loop iteration typeerror


【解决方案1】:

应该是:

for k in Tab:
   print k

len(Tab) 给出 Tab 的长度。

【讨论】:

  • OP 想要迭代 index,而不是元素。
【解决方案2】:

如果您想选择迭代索引或实际值,可以使用enumerate

for i, k in enumerate(Tab):
    print(Tab[i]) # print(k)

您不能迭代 len(Tab),因为它是一个标量,而不是一个可迭代对象。


Tab 是一个 numpy 数组,它们具有漂亮的 __repr__ 实现。为什么不只是print(Tab)

【讨论】:

    【解决方案3】:
    import numpy as np
    ar = np.asarray([1,2,3])
    a_list = list(ar)
    

    对于您的代码:

    for k in list(Tab):
    

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 1970-01-01
      • 2021-07-11
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2020-05-10
      • 1970-01-01
      相关资源
      最近更新 更多