【问题标题】:list of list from text files and accessing index of the lists来自文本文件的列表列表和访问列表的索引
【发布时间】:2017-11-27 09:37:24
【问题描述】:

我有两个文本文件,每个文件有 10 个值。现在我想将这 10 个值作为两个列表包含在一个列表中并访问列表列表的索引。但问题是我收到一条错误消息,“列表索引必须是整数,而不是元组”。任何建议将不胜感激。

在我拥有的第一个文件中 0.001 0.017 0.07 0.09 0.05 0.02 0.014 0.014 0.021 0.033

在我的第二个文件中

0.001 0.01 0.0788 0.09 0.0599 0.0222 0.014 0.01422 0.0222 0.033

import numpy as np

d=[]
one = np.loadtxt('one.txt')
two=np.loadtxt('two.txt')

d.append(one)
d.append(two)


#I get this error "list indices must be integers, not tuple ", when 
# I try to access the index of my lists inside the list

print (d[0,:])

【问题讨论】:

标签: python list numpy


【解决方案1】:

你从 numpy 开始,所以坚持使用 numpy!您不希望 onetwo 在列表中,而是希望它们作为 2d numpy 数组的行:

d = np.array([one, two])

d
# array([[ 0.001  ,  0.017  ,  0.07   ,  0.09   ,  0.05   ,  0.02   ,
#          0.014  ,  0.014  ,  0.021  ,  0.033  ],
#        [ 0.001  ,  0.01   ,  0.0788 ,  0.09   ,  0.0599 ,  0.0222 ,
#          0.014  ,  0.01422,  0.0222 ,  0.033  ]])
type(d)
# <class 'numpy.ndarray'>
d.shape
# (2, 10)
d[0, :]
# array([ 0.001,  0.017,  0.07 ,  0.09 ,  0.05 ,  0.02 ,  0.014,  0.014,
#         0.021,  0.033])
d[:, 4]
# array([ 0.05  ,  0.0599])

等等

【讨论】:

  • 感谢保罗的详细解答。现在我明白我错在哪里了。再次感谢您
【解决方案2】:

d[0,:] 不是一个东西。不知道你想在这里做什么。试试d[0]

一些附加信息:

d 是一个二维列表。 (它是一个列表的列表。)下面是一个展示如何访问某些部分的示例:

>>> d = [[1, 2, 3], [4, 5, 6]]
>>> d[0]
[1, 2, 3]
>>> d[1]
[4, 5, 6]
>>> d[0][2]
3
>>> d[0][1:]
[2, 3]
>>> d[1][:2]
[4, 5]
>>> e = [d[0][1], d[1][1]]
>>> e
[2, 5]

有意义吗?

【讨论】:

  • 假设我想访问每个列表的第二个值,我该怎么做?
  • d[0][1]d[1][1]
猜你喜欢
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多