【问题标题】:Accessing elements in a list of arrays in python在python中访问数组列表中的元素
【发布时间】:2013-12-02 00:20:05
【问题描述】:
c = []
Indices = []
list_ = iter([0.10,0.16,0.25,0.50,0.75,0.90])
for i in list_:
    b = around((total_*i), decimals = 2)
    t = where(fcol == find_nearest(fcol,b))
    c.append(b)
    indices.append(t)
    print t #gives:

(array([485]),)
(array([523]),)
(array([576]),)
(array([733]),)
(array([963]),)
(array([1254]),)

当我在 for 循环外打印索引列表时,它看起来像:

print indices #gives:    
[(array([485]),), (array([523]),), (array([576]),), (array([733]),), (array([963]),), (array([1254]),)]

虽然所需的输出是一个类似的列表:

[485, 523, 576, 733, 963, 1254] 

问题: 我用来编写“数组列表”的这种方法是一个好方法吗?(我认为可能有更有效的方法)如果是,我如何访问列表中的数字(数组元素)?

【问题讨论】:

  • 您将type 应用于indices(小写),这与第一个代码sn-p 使用的Indices(大写)不同。保持一致。
  • 避免此错误的一种简单方法是遵循 python 约定并将所有变量都小写。
  • @SethMMorton,感谢您的评论。我为此编辑了我的问题,但主要问题仍然存在。有什么想法吗?
  • 为什么奇怪地调用iter 而不是直接遍历列表?
  • 好点!由于某种我现在不记得的原因,我在列表之前添加了那个 iter,但是没有它它工作得很好!谢谢

标签: python arrays list printing


【解决方案1】:

您可能已经在别处创建了indices 函数。

>>> Indices = []
>>> type(Indices)
<type 'list'>

所以你需要注意大小写。

【讨论】:

  • 谢谢亚伦。我编辑了我的问题并删除了关于类型的愚蠢部分!
【解决方案2】:

这解决了我的问题:

indices.append(list(t[0])) 
    #which gives:    
[[485], [523], [576], [733], [963], [1254]]

然后:

for x in indices:
    print (x[0])

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    相关资源
    最近更新 更多