【问题标题】:Foreach on Multiple 2 Dimensional Lists:Foreach 在多个二维列表上:
【发布时间】:2014-09-16 08:53:42
【问题描述】:

这是我遇到的问题的一个示例:

A = [
    [1, 2, 3, 4, 5, 6],
    [7, 8, 9, 10, 11, 12],
    [13, 14, 15, 16, 17, 18]
]

B = [
    ['1', '2', '3', '4', '5', '6'],
    ['7', '8', '9', '10', '11', '12'],
    ['13', '14', '15', '16', '17', '18']
]

for a, b in A, B:
    for ai, bi in a, b:
        if ai == int(bi):
            print 'it worked!'

此代码在第 13 行给我一个错误:ValueError: too many values to unpack

我希望让ab 指向 6 个元素的列表,例如[1, 2, 3, 4, 5, 6]['1', '2', '3', '4', '5', '6'],分别用于第一次迭代。

我试过为每个二维数组设置一个迭代器,就像上面一样,我还尝试使用 12 个变量,以防 Python 试图将 6 元素列表中的每个元素传递给它自己的变量(6 个a 和 6 代表 b,如 a1, ... a6, b1, ... b6

谁能指出这里发生了什么,或者解释一下如何获得我正在寻找的结果?

【问题讨论】:

    标签: python arrays list iterator


    【解决方案1】:

    你可以这样做:

    for a, b in zip(A, B):
        if a == map(int, b):
            print 'it worked!'
    

    如果你想打印一个it worked!,你可以这样做:

    if all(a == map(int, b) for a, b in zip(A, B)):
        print 'it worked!'
    

    zip 返回一个长度是两个列表中最小的对的列表,所以它会说它适用于这些:

    A = [[1, 2]]
    B = [['1', '2'], ['3', '4']]
    

    如果您想避免这种情况,您可以import itertools 并将zip 替换为izip_longeset

    【讨论】:

    • 谢谢!我忘记了 zip 函数,我什至没有意识到我忘记映射预期的函数,所以我会在我的问题中更正它。
    【解决方案2】:

    如果要同时遍历多个列表,需要使用zip(https://docs.python.org/2/library/functions.html#zip):

    for a, b in zip(A,B):
        # a and b are now the inner lists
        print "It worked!"
    

    我不确定你想用你的a == int(b) 语句实现什么,所以我把它省略了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 2021-10-02
      • 1970-01-01
      • 2019-09-04
      相关资源
      最近更新 更多