从itertools.combinations列表中删除括号

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

Remove parenthesis from itertools.combinations list

问题

我想制作一个在一定范围内的数字组合的列表,并逐行打印它们,但不要包含括号。以下是我迄今为止编写的代码。

  1. import itertools
  2. x = range(1, 4)
  3. y = list(itertools.combinations(x, 2))
  4. combos = []
  5. for i in range(len(y)):
  6. combos.append(y[i])
  7. print(combos[i])

输出是:

  1. 1, 2
  2. 1, 3
  3. 2, 3

我需要它以不包含括号的方式打印输出。我已经寻找了各种解决方案,但迄今为止都没有找到任何东西。任何帮助将不胜感激。

英文:

I want to make a list of all possible combinations in a range of numbers, and print them line by line without surrounding parentheses. Here is the code I've built so far.

  1. import itertools
  2. x = range(1,4
  3. y = list(itertools.combinations(x,2))
  4. combos = []
  5. for i in range(len(y)):
  6. combos.append(y[i])
  7. print(combos[i])

The output is

  1. (1,2)
  2. (1,3)
  3. (2,3)

I need it to print the output without surrounding parentheses. I've looked high and low for a solution, but so far I can't find anything. Any help would be much appreciated.

答案1

得分: 1

这是一个简单的方法来做到这一点。

  1. import itertools
  2. x = range(1, 4)
  3. y = list(itertools.combinations(x, 2))
  4. for pair in y:
  5. print(*pair)

如果你真的想要分隔逗号,你可以这样做:

  1. import itertools
  2. x = range(1, 4)
  3. y = list(itertools.combinations(x, 2))
  4. for pair in y:
  5. print(f"{pair[0]},{pair[1]}")
英文:

Here's a simple way to do this.

  1. import itertools
  2. x = range(1,4)
  3. y = list(itertools.combinations(x,2))
  4. for pair in y:
  5. print(*pair)

If you really want the separating commas, you could do this:

  1. import itertools
  2. x = range(1,4)
  3. y = list(itertools.combinations(x,2))
  4. for pair in y:
  5. print(f"{pair[0]},{pair[1]}")

huangapple
  • 本文由 发表于 2023年6月22日 00:47:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525506.html
匿名

发表评论

匿名网友

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

确定