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

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

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

使用嵌套循环:

  1. >>> num = 4
  2. >>> for i in range(num):
  3. ... for j in range(i+1, num+1):
  4. ... print((i, j))
  5. ...
  6. (0, 1)
  7. (0, 2)
  8. (0, 3)
  9. (0, 4)
  10. (1, 2)
  11. (1, 3)
  12. (1, 4)
  13. (2, 3)
  14. (2, 4)
  15. (3, 4)

使用 itertools

  1. >>> import itertools
  2. >>> print(*itertools.combinations(range(num+1), 2), sep="\n")
  3. (0, 1)
  4. (0, 2)
  5. (0, 3)
  6. (0, 4)
  7. (1, 2)
  8. (1, 3)
  9. (1, 4)
  10. (2, 3)
  11. (2, 4)
  12. (3, 4)
英文:

Using nested loops:

  1. >>> num = 4
  2. >>> for i in range(num):
  3. ... for j in range(i+1, num+1):
  4. ... print((i, j))
  5. ...
  6. (0, 1)
  7. (0, 2)
  8. (0, 3)
  9. (0, 4)
  10. (1, 2)
  11. (1, 3)
  12. (1, 4)
  13. (2, 3)
  14. (2, 4)
  15. (3, 4)

Using itertools:

  1. >>> import itertools
  2. >>> print(*itertools.combinations(range(num+1), 2), sep="\n")
  3. (0, 1)
  4. (0, 2)
  5. (0, 3)
  6. (0, 4)
  7. (1, 2)
  8. (1, 3)
  9. (1, 4)
  10. (2, 3)
  11. (2, 4)
  12. (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:

确定