从raw_input打印不带括号和逗号的排列?

时间:2012-04-25 16:43:10

标签: python

我想在没有括号和逗号的情况下输出我的代码:

import itertools
import pprint
run = 1
while run != 0:
    number = raw_input('\nPlease type between 4 and 8 digits and/or letters to run permutation: ')

    if len(number) >= 4 and len(number) <= 8:
        per = list(itertools.permutations(number))
        pprint.pprint(per)
        print '\nNumber of possible combinations: ',len(per),'\n'

    elif number == 'exit':
        run = 0

    else:
        raw_input('length must be 4 to 8 digits and/or letters. Press enter to exit')
        run = 0

因此它打印出一个列表,其中每个组合都在一个新行中。如何打印它而不使用括号和逗号?我仍然希望能够调用per [x]来获得某种组合。任何帮助赞赏!谢谢。

7 个答案:

答案 0 :(得分:0)

不应使用pprint.pprint来打印对象的repr,而应使用常规打印,这不会将换行更改为文字'\n'

print('\n'.join(map(str, per)))

必须将str映射到per,因为string.join需要一个字符串列表。

修改:示例输出显示每个排列都没有逗号分隔,并且您没有看到列表的括号:

>>> print('\n'.join(map(str, itertools.permutations([0, 1, 2, 3]))))
(0, 1, 2, 3)
(0, 1, 3, 2)
(0, 2, 1, 3)
(0, 2, 3, 1)
(0, 3, 1, 2)
(0, 3, 2, 1)
(1, 0, 2, 3)
(1, 0, 3, 2)
(1, 2, 0, 3)
(1, 2, 3, 0)
(1, 3, 0, 2)
(1, 3, 2, 0)
(2, 0, 1, 3)
(2, 0, 3, 1)
(2, 1, 0, 3)
(2, 1, 3, 0)
(2, 3, 0, 1)
(2, 3, 1, 0)
(3, 0, 1, 2)
(3, 0, 2, 1)
(3, 1, 0, 2)
(3, 1, 2, 0)
(3, 2, 0, 1)
(3, 2, 1, 0)

答案 1 :(得分:0)

pprint.pprint替换为:

for line in per:
    print ''.join(line)

以下是代码段的更紧凑版本:

import itertools

while True:
    user_input = raw_input('\n4 to 8 digits or letters (type exit to quit): ')
    if user_input == 'exit':
        break
    if 4 <= len(user_input) <= 8:
        # no need for a list here, just unfold on the go
        # counting via enumerate
        for i, p in enumerate(itertools.permutations(user_input)):
            print(''.join(p))
        print('#permutations: %s' % i)

答案 2 :(得分:0)

循环遍历它们并打印由您喜欢的角色(此处为空格)分隔的每一个:

#pprint.pprint(per)
for p in per:
    print ' '.join(p)

答案 3 :(得分:0)

只需用您自己的代码替换pprint()即可输出数据。像这样:

for i in per:
    print i

答案 4 :(得分:0)

使用join()

per = list(itertools.permutations(number))
        for x in per:
            print "".join(x)
        print '\nNumber of possible combinations: ',len(per),'\n'

答案 5 :(得分:0)

我会将列表转换为字符串,然后删除括号和逗号:

x = str(per)[1 : -1]
x.replace(",", "")
print x

答案 6 :(得分:0)

答案的其他变体

(lambda x: ''.join(x))(x)

相关问题