2012-04-25 75 views
-1

我要讓我的代碼的輸出,而不括號和逗號:從raw_input中打印不帶括號和逗號的排列?

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]來獲得某種組合。任何幫助感謝!謝謝。

+0

「沒有得到括號和逗號」 你能舉一個你想看到什麼格式的例子嗎?每行應該只包含數字(用空格分隔,例如'0 1 2 3'),還是每行看起來像列表中條目的repr(例如'(0,1,2,3)')? – Darthfett 2012-04-25 17:08:25

回答

0

使用join()

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

這是我想要的輸出!謝謝! – xrefor 2012-04-25 17:09:08

+0

請注意,join(至少在python 3.x中)不會對對象進行隱式字符串轉換,所以這個代碼不是未來的證明(儘管print語句暗示了這一點)。 Guido自己給出了[爲什麼沒有隱式字符串轉換](http://mail.python.org/pipermail/python-ideas/2010-October/008358.html)的理性 - 來檢測錯誤的代碼。 – Darthfett 2012-04-25 17:31:36

0

而不是使用pprint.pprint,這將打印對象的再版的,你應該使用常規的打印,這不會改變換行到文字'\n'

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

只好在per映射str,如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) 
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) 
+0

謝謝!這真的幫助我看到我可以做出的簡單更改,以使我的代碼更緊湊。偉大的加法! – xrefor 2012-04-26 10:10:51

0

遍歷它們並打印每一個你所喜歡的字符(這裏是空格)分隔:

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

只需更換pprint()用你自己的代碼位輸出數據。事情是這樣的:

for i in per: 
    print i 
+0

我嘗試過: 因爲我在每個: 打印我 我仍然得到parantheses和逗號。我想要沒有它的輸出。 – xrefor 2012-04-25 17:03:44

0

我將列表轉換爲字符串,然後去掉括號和逗號:

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

答案的其他變化

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