使用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函数。我从每个列表前面的列表[0]位置的值中减去list [2]位置中的值。然后我将这些结果附加到另一个列表(exit_scores)。
最后,我想将exit_scores(现在为a)添加到原始列表中。
所以我使用了我的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列表被添加到T:
的第一个列表的末尾[[1, 0, 1, 0, 2, 2, -1], [1, 0, 3], [0, 5, 2], [3, -1, 2]]
对于我的生活,我无法弄清楚我做错了什么......
答案 0 :(得分:4)
这次是list.append()
,而不是list.extend()
:
def score_add(team, exit_scores):
for t, e in zip(team, exit_scores)
t.append(e)
print team
B
是一个列表列表,而exit_scores
是一个整数列表。
修改:以下是整个代码的清理版本:
for t, b in zip(T, B):
t.extend(b)
t.append(t[2] - t[0])
答案 1 :(得分:0)
我会咬人:
map(lambda x, y: x + y + [x[0] - y[0]], T, B)
产量:
[[1, 0, 1, 0], [1, 0, 3, -2], [0, 5, 2, -2], [3, -1, 2, 1]]
此外,它可以在列表理解中完成:
[x+y+[x[0]-y[0]] for x, y in zip(T, B)]