返回的翻译部分:Python:给定一个数字,返回从0到给定数字的元组。

huangapple go评论66阅读模式
英文:

Python: Given a number return tuple from 0, a number given

问题

以下是要翻译的内容:

给定:num=4

期望:(0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)(以元组形式)

英文:

Hi I would like to knoq how I can achieve this in python.

given: num=4

expect: (0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4) (in tuple)

答案1

得分: 1

使用嵌套循环:

>>> num = 4
>>> for i in range(num):
...     for j in range(i+1, num+1):
...         print((i, j))
...
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

使用 itertools

>>> import itertools
>>> print(*itertools.combinations(range(num+1), 2), sep="\n")
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
英文:

Using nested loops:

>>> num = 4
>>> for i in range(num):
...     for j in range(i+1, num+1):
...         print((i, j))
...
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

Using itertools:

>>> import itertools
>>> print(*itertools.combinations(range(num+1), 2), sep="\n")
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

huangapple
  • 本文由 发表于 2023年3月7日 08:32:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定