我正在尝试在for中创建一个列表,我这样做:
for i in PSOE_data:
if i[0] + i[1] + i[2] != 0:
newList.append(i)
PSOE_list = PrettyTable(["Digital Chanel", "State", "Hour", "Minute", "Second"])
PSOE_list.align["Digital Chanel"] = "c" # Alinhamento pela esquerda
PSOE_list.padding_width = 1 # Espaçamento entre colunas (default)
PSOE_list.add_row([newList[i][3], newList[i][4], newList[i][0], newList[i][1], newList[i][2]])
print PSOE_list
但有追溯说:
PSOE_list.add_row([newList[i][3], newList[i][4], newList[i][0], newList[i][1], newList[i][2]])
TypeError: list indices must be integers, not list
我该如何处理? 顺便说一下,我正在使用PrettyTable包。
谢谢!
答案 0 :(得分:0)
您的问题是缺少一些信息......您要打印清单吗?如果是这种情况,也许我的“printMatrix”功能会帮助你。
def printMatrix(matrix):
for row in matrix:
for element in row:
print str(element) + '\t',
print
some_list = [[0, 0, 0.0, 17, 2], [0, 0, 0.0, 25, 2],\
[0, 1, 0.017646, 11, 1], [0, 1, 0.028056, 10, 1],\
[0, 1, 0.028056, 12, 1], [0, 1, 1.032746, 10, 0],\
[0, 1, 1.032746, 12, 0], [0, 1, 1.091776, 11, 0]]
another_list = ["Digital Chanel", "State", "Hour", "Minute", "Second"]
printMatrix(some_list.insert(0,another_list))
Digital Chanel State Hour Minute Second
0 0 0.0 17 2
0 0 0.0 25 2
0 1 0.017646 11 1
0 1 0.028056 10 1
0 1 0.028056 12 1
0 1 1.032746 10 0
0 1 1.032746 12 0
0 1 1.091776 11 0
我已经安装了“漂亮的桌子”,所以让我们一起去吧。最后,我仍然不确定我们是否在同一页面,检查我的代码:
import prettytable
newList = [] # empty list, to be filled with ROWS from PSOE_data
PSOE_data = some_list # see code above...
for row in PSOE_data: # loop through every row in PSOE_data
if sum(row[0:3]) != 0: # if sum three first elements != 0
#my note: why doesn't python care about type "int" or "float"?
newList.append(row) # appends the entire row to newList
# at this stage "newList" is a list of lists: (is this what you want?)
# [[0, 1, 0.017646, 11, 1],
# [0, 1, 0.028056, 10, 1],
# [0, 1, 0.028056, 12, 1],
# [0, 1, 1.032746, 10, 0],
# [0, 1, 1.032746, 12, 0],
# [0, 1, 1.091776, 11, 0]]
PSOE_list = prettytable.PrettyTable(\
["Digital Chanel","State", "Hour", "Minute", "Second"])
PSOE_list.align["Digital Chanel"] = "c"
PSOE_list.padding_width = 1
# Note how it is useful to avoid "i,j,k" notation when looping through
# rows, i.e. when the counter is not an integer number.
# this is what you are trying to do and it is doomed to fail because:
# row = [0, 1, 1.091776, 11, 0]
# PSOE_list.add_row([ newList[row][3], newList[row][4], newList[row][0], newList[row][1], newList[row][2] ])
# But if you do:
for row in newList:
PSOE_list.add_row([ row[3], row[4], row[0], row[1], row[2] ])
# You get:
print PSOE_list
+----------------+-------+------+--------+----------+
| Digital Chanel | State | Hour | Minute | Second |
+----------------+-------+------+--------+----------+
| 11 | 1 | 0 | 1 | 0.017646 |
| 10 | 1 | 0 | 1 | 0.028056 |
| 12 | 1 | 0 | 1 | 0.028056 |
| 10 | 0 | 0 | 1 | 1.032746 |
| 12 | 0 | 0 | 1 | 1.032746 |
| 11 | 0 | 0 | 1 | 1.091776 |
+----------------+-------+------+--------+----------+