在python中创建元组集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21344938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:38:06  来源:igfitidea点击:

creating sets of tuples in python

pythontuples

提问by Chung

How do i create a set of tuples with each tuple containing two elements? Each tuple will have an xand yvalue: (x,y)I have the numbers 1 through 50, and want to assign xto all values 1 through 50 and yalso 1 through 50.

如何创建一组元组,每个元组包含两个元素?每个元组都有一个xandy值:(x,y)我有 1 到 50 的数字,并且想要分配x1 到 50 以及y1 到 50 的所有值。

S = {(1,1),(1,2),(1,3),(1,4)...(1,50),(2,1)......(50,50)}

I tried

我试过

positive = set(tuple(x,y) for x in range(1,51) for y in range(1,51))

but the error message says that a tuple only takes in one parameter. What do I need to do to set up a list of tuples?

但是错误消息说一个元组只接受一个参数。我需要做什么来设置元组列表?

采纳答案by inspectorG4dget

mySet = set(itertools.product(range(1,51), repeat=2))

OR

或者

mySet = set((x,y) for x in range(1,51) for y in range(1,51))

回答by senshin

tupleaccepts only one argument. Just explicitly write in the tuple instead using parentheses.

tuple只接受一个参数。只需在元组中明确写入而不是使用括号。

#                  vvvvv
>>> positive = set((x,y) for x in range(1,5) for y in range(1,5))
>>> positive
{(1, 2), (3, 2), (1, 3), (3, 3), (4, 1), (3, 1), (4, 4), (2, 1), (2, 4), (2, 3), (1, 4), (4, 3), (2, 2), (4, 2), (3, 4), (1, 1)}