2024-10-01 05:02:32 发布
网友
我正在学习Python 3的TreeHouse元组教程,以下代码中出现此错误:
def combo(iter1, iter2): ltup = [] for a in iter1: for b in iter2: ltup.append(tuple([a, b])) return ltup
我应该如何修复它,为什么我的解决方案是错误的?你知道吗
我使用了zip,但它没有通过挑战:
zip
你可以用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)
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.
list
i-th tuple
i-th
因为您的iterables具有相同的长度,所以这应该和您预期的一样有效。你知道吗
def combo(iter1, iter2): return zip(iter1, iter2)
更新:对于python 3
为了完整起见,在使用哪个python版本的问题中没有提到。如果您使用的是python3,^{}将返回一个iterable,因此需要显式地将其转换为list:
def combo(iter1, iter2): return list(zip(iter1, iter2))
你可以用
zip
来得到答案。你知道吗您不需要嵌套循环。请尝试以下代码:
或者另一种最短的变体,我猜:
zip(iter1, iter2)
你只需要把这些iterables放在一起:
因为您的iterables具有相同的长度,所以这应该和您预期的一样有效。你知道吗
更新:对于python 3
为了完整起见,在使用哪个python版本的问题中没有提到。如果您使用的是python3,^{} 将返回一个iterable,因此需要显式地将其转换为list:
相关问题 更多 >
编程相关推荐