简体   繁体   English

使用列表理解的 2 个元素的元组列表

[英]List of tuples of 2 elements using a list comprehension

I want to use a list comprehension to initialize a list of tuples that has a 2 elements in it, my attempt is as follows:我想使用列表推导来初始化其中包含 2 个元素的元组列表,我的尝试如下:

SIZE = 10
possible_positions = [(x, y) for x, y in range(0, SIZE)]

But that gives me an error:但这给了我一个错误:

TypeError: cannot unpack non-iterable int object

What is the right way to do it?正确的方法是什么? I know I can use a for loop, but I want to know anyway.我知道我可以使用 for 循环,但我还是想知道。

range return a single value per iteration, you should use zip combined with range in the following way: range每次迭代返回一个值,您应该使用ziprange结合,方法如下:

zip(range(SIZE), range(SIZE))

Using zip will also save you the trouble of creating the list of tuples so calling list(zip(range(SIZE), range(SIZE))) will give you the end result使用zip还将为您省去创建元组列表的麻烦,因此调用list(zip(range(SIZE), range(SIZE)))将为您提供最终结果

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

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