没有获得创建给定两个列表的元组列表的正确输出

2024-10-01 05:02:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python 3的TreeHouse元组教程,以下代码中出现此错误: enter image description here

def combo(iter1, iter2):
    ltup = []
    for a in iter1:
        for b in iter2:
            ltup.append(tuple([a, b]))
    return ltup

enter image description here

我应该如何修复它,为什么我的解决方案是错误的?你知道吗

我使用了zip,但它没有通过挑战: enter image description here


Tags: 代码inforreturndef错误教程元组
3条回答

你可以用zip来得到答案。你知道吗

a = [1,2,3]
b = [4,5,6]
ans = zip(a,b)
[(1, 4), (2, 5), (3, 6)]

您不需要嵌套循环。请尝试以下代码:

def combo(iter1, iter2):
    ltup = []
    for a,b in zip(iter1, iter2):
            ltup.append((a, b))
    return ltup

print combo([1,2,3],[3,2,1])

或者另一种最短的变体,我猜: zip(iter1, iter2)

[(1, 3), (2, 2), (3, 1)]

你只需要把这些iterables放在一起:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence.

因为您的iterables具有相同的长度,所以这应该和您预期的一样有效。你知道吗

def combo(iter1, iter2):
    return zip(iter1, iter2)

更新:对于python 3

为了完整起见,在使用哪个python版本的问题中没有提到。如果您使用的是python3,^{}将返回一个iterable,因此需要显式地将其转换为list:

def combo(iter1, iter2):
    return list(zip(iter1, iter2))

相关问题 更多 >