-1

我想让我的代码输出不带括号和逗号:

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] 来获得某种组合。任何帮助表示赞赏!谢谢你。

4

7 回答 7

0

而不是 using pprint.pprint,它将打印对象的 repr ,您应该使用常规打印,它不会将换行符更改为文字'\n'

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

必须 map strover 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)
于 2012-04-25T16:51:32.150 回答
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)
于 2012-04-25T16:52:27.200 回答
0

循环遍历它们并打印出由你喜欢的字符分隔的每一个(这里是空格):

#pprint.pprint(per)
for p in per:
    print ' '.join(p)
于 2012-04-25T16:52:53.347 回答
0

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

for i in per:
    print i
于 2012-04-25T16:53:05.343 回答
0

采用join()

per = list(itertools.permutations(number))
        for x in per:
            print "".join(x)
        print '\nNumber of possible combinations: ',len(per),'\n'
于 2012-04-25T16:55:02.223 回答
0

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

x = str(per)[1 : -1]
x.replace(",", "")
print x
于 2012-04-25T16:57:00.197 回答
0

答案的其他变体

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

于 2013-01-23T09:23:42.877 回答