【发布时间】:2011-11-03 17:08:11
【问题描述】:
在 python 2.7 中工作。
我有两个列表(简化以使解释更清楚):
T = [[1, 0], [1, 0], [0, 5], [3, -1]]
B = [[1], [3], [2], [2]]
还有三个功能。
def exit_score(list):
exit_scores = []
length = len(list)
for i in range(0, length):
score = list[i][2] - list[i][0]
exit_scores.append(score)
return exit_scores
首先我将 B 的对应值附加到 T 中的对应列表中:
def Trans(T, B):
for t, b in zip(T, B):
t.extend(b)
a = exit_score(T)
b = T
score_add(b, a)
然后,使用前面列出的 exit_score 函数。我从每个列表的 list[0] 位置中的值中减去 list[2] 位置中的值。然后我将这些结果附加到另一个列表(exit_scores)。
最后,我想将 exit_scores(现在是一个)添加到原始列表中。
所以我使用我的 score_add(b, a) 函数:
score_add(team, exit_scores):
for t, e in zip(team, exit_scores)
t.extend(e)
print team
如果一切正常,我会得到这样的输出:
[[1,0,1,0], [1,0,3,-2], [0,5,2,-2], [3,-1,2,1]]
相反,我收到一个 TypeError,告诉我我无法迭代整数。但是我已经尝试打印 a 和 b 并且都是列表形式!
当我更改代码以确保退出分数在列表中时:
def Trans(T, B):
es = []
for t, b in zip(T, B):
t.extend(b)
es.append(exit_score(T))
score_add(T, es)
整个exit_scores列表(es)被添加到T的第一个列表的末尾:
[[1, 0, 1, 0, 2, 2, -1], [1, 0, 3], [0, 5, 2], [3, -1, 2]]
对于我的一生,我无法弄清楚我做错了什么......
【问题讨论】:
-
您需要重新考虑所有代码。它方式比非常简单的操作要复杂。
标签: python list map for-loop zip