【问题标题】:Trouble with zip function in for loop; pythonfor循环中的zip功能有问题; Python
【发布时间】: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


【解决方案1】:

这次是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])

【讨论】:

  • 没错。你知道我可以学习这些命令的好资源吗?显然,这个领域有点弱点……
  • @BurtonGuster:我将从一些 Python 教程开始。官方教程挺好的,我也喜欢How to Think Like a Computer Scientist
【解决方案2】:

我会咬人的:

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)]

【讨论】:

  • 你复制了 OP 不想要的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2011-01-26
  • 2016-05-05
  • 1970-01-01
  • 2011-07-30
  • 2021-10-21
相关资源
最近更新 更多