在for循环中使用zip函数遇到问题;python
我在使用 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 函数。我从每个列表的第一个位置的值中减去第二个位置的值。然后把这些结果添加到另一个列表(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]]
但实际上,我遇到了一个类型错误,提示我不能对一个整数进行迭代。但是我已经尝试打印 a 和 b,发现它们都是列表形式的!
当我修改代码,确保 exit_scores 是一个列表时:
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]]
我真搞不明白我哪里出错了……
2 个回答
0
我来试试:
map(lambda x, y: x + y + [x[0] - y[0]], T, B)
让我们来看看“yield”的用法:
[[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)]
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])