【问题标题】:I want to permute given input(numbers, string, float etc) to the length(given)我想将给定的输入(数字、字符串、浮点数等)置换为长度(给定)
【发布时间】:2020-04-12 03:52:39
【问题描述】:

我的代码,请在这里阅读我的问题,如果可以的话,请给我更好的输出。

import itertools

variable, r = input().split()
r = int(r)
l = list(itertools.permutations(variable,r))
for i in l:
    for j in range(0,r):
        print(f'{i[j]}{i[j+1]}')

如果我的输入是HACK 2

我的输出应该是这样的

AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH

我在这一行出现元组索引错误print(f'{i[j]}{i[j+1]}')

【问题讨论】:

  • 你可以用print(''.join(i))替换你的内循环
  • i[j+1] 将在 j == r-1 在内循环中失败,因为 i 只有 r 元素。

标签: python python-3.x tuples permutation itertools


【解决方案1】:
f'{i[j]}{i[j+1]}'

这代表来自i 的两个项目。但是我们想使用来自i 的所有项目,不管有多少。比如我们输入HACK 3itertools.permutations 会产生类似('H', 'A', 'C') 的排列,我们想要输出单个项目'HAC' - 我们不想再次循环并分别得到'HA''AC'

我们想要做的只是将所有项目连接成一个字符串。我们使用内置的.join 字符串方法来做到这一点:

# Also, there is no need to make a list ahead of time; we can iterate directly
# on the itertools results.
for item in itertools.permutations(variable,r):
    print(''.join(item))
    # Another way is to pass the letters as separate argument to `print`,
    # and let it do the joining implicitly:
    # print(*item, sep='')
    # This is one of those neat things that becomes possible due to `print`
    # becoming a function in 3.x.

【讨论】:

  • 谢谢!你的解释很有帮助。
【解决方案2】:

关键是您的元组只有两个元素,但您的索引是从 0 到 r,这意味着在系列内部它将来自 0,1,2。这是从索引中创建错误元组

系列的权利将是

for i in l:
    for j in range(0,r-1):
        print(f'{i[j]}{i[j+1]}')

【讨论】:

  • 这是错误的。 r 是要打印的值的数量。 f 字符串被硬编码为打印两个值,这不好,因为r 可以是除 2 之外的其他值。
猜你喜欢
  • 2015-10-07
  • 1970-01-01
  • 2018-05-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
相关资源
最近更新 更多