简体   繁体   English

2d列表不起作用

[英]2d list not working

I am trying to create a 2D list, and I keep getting the same error "TypeError: list indices must be integers, not tuple" I do not understand why, or how to use a 2D list correctly. 我正在尝试创建一个2D列表,我一直得到相同的错误“TypeError:列表索引必须是整数,而不是元组”我不明白为什么,或者如何正确使用2D列表。

Total = 0
server = xmlrpclib.Server(url);
mainview = server.download_list("", "main")
info = [[]]
info[0,0] = hostname
info[0,1] = time
info[0,2] = complete
info[0,3] = Errors
for t in mainview:
  Total += 1
  print server.d.get_hash(t)
  info[Total, 0] = server.d.get_hash(t)
  info[Total, 1] = server.d.get_name(t)
  info[Total, 2] = server.d.complete(t)
  info[Total, 3] = server.d.message(t)

  if server.d.complete(t) == 1:
    Complete += 1
  else:
    Incomplete += 1
  if (str(server.d.message(t)).__len__() >= 3):
    Error += 1
info[0,2] = Complete
info[0,3] = Error

everything works, except for trying to deal with info. 一切正常,除了试图处理信息。

Your mistake is in accessing the 2D-list, modify: 你的错误在于访问2D列表,修改:

info[0,0] = hostname
info[0,1] = time
info[0,2] = complete
info[0,3] = Errors

to: 至:

info[0].append(hostname)
info[0].append(time)
info[0].append(complete)
info[0].append(Errors)

Same goes to info[Total, 0] and etc. info[Total, 0]等同样如此。

The way you created info , it is a list containing only one element, namely an empty list. 您创建info的方式,它是一个只包含一个元素的列表,即一个空列表。 When working with lists, you have to address the nested items like 使用列表时,您必须解决嵌套项目

info[0][0] = hostname

For initialization, you have to create a list of lists by eg 对于初始化,您必须通过例如创建列表列表

# create list of lists of 0, size is 10x10
info = [[0]*10 for i in range(10)]

When using numpy arrays, you can address the elements as you did. 使用numpy数组时,您可以像处理那样处理元素。

One advantage of "lists of lists" is that not all entries of the "2D list" shall have the same data type! “列表列表”的一个优点是并非“2D列表”的所有条目都具有相同的数据类型!

info = [[] for i in range(4)] # create 4 empty lists inside a list
info[0][0].append(hostname)
info[0][1].append(time)
info[0][2].append(complete)
info[0][3].append(Errors)

You need to create the 2d array first. 您需要先创建2d数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM