简体   繁体   English

Python - 对元组的列表理解

[英]Python - list comprehension over tuple

I have two arrays inside tuple and need to iterate over it.我在元组中有两个 arrays 并且需要对其进行迭代。

recs = ([1,2,3], [4,5,6])
[print(f, s) for f, s in recs]

But got error:但出现错误:

ValueError: too many values to unpack (expected 2)

How can I do it?我该怎么做?

PS print only for debug example PS 打印仅用于调试示例

zip is the function you're after: zip是您所追求的 function:

_ = [print(*values, end=' ') for values in zip(*recs)]

values here is the (f, s) tuple.这里的values(f, s)元组。 This way it will generalize beyond just 2 lists这样,它将泛化到 2 个列表之外

Do you just want to iterate over each of the 2 arrays?您是否只想遍历 2 个 arrays 中的每一个? Like: [print(array) for array in recs]喜欢: [print(array) for array in recs]

Or do you want to iterate over the values in each array as well, like: [[print(num) for num in array] for array in recs]或者您是否也想遍历每个数组中的值,例如: [[print(num) for num in array] for array in recs]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM