2012-06-08 25 views
0

鑑於本字典自定義排列python?

dictt={2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} 

我需要做一個自定義排列。

輸入中的數字會告訴您輸出的時間。

輸入也會指向正在排列的字母。例如

。 「34」將使程序返回第一個序列的第一個字母,並逐個添加第二個序列的所有3個字母。那麼它將採用第一個序列的第二個字母並加上第二個序列的所有3個字母b + d = bd b + e = be b + d = a + d = ad + e = ae a + d = af f = bf 然後第三個字母 c + d = cd c + e = ce c + f = cf 因此,當您輸入34時,如果輸入爲3個數字,它將返回ad af af bd be bf cd ce cf 。那麼如果輸入是一個數字,則輸出將是成對的3. 。那麼輸出將只是列出的相應序列。 ex: "2" would return a b c

def permuteString(numString): 
    array=[] 
    original={2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} 
    for a,b in original.iteritems(): 
     print a,b 
     for c in b: 
      print c 

    return array 

stuff=permuteString("234") 

到目前爲止,我所做的只是拉字典出

+0

什麼在「34則 「4」? –

+0

34是什麼意思。在字典中,'3:'abc'','4:'def''。如果你輸入'34',爲什麼不輸出'dg df di eg ef ff ff fi'?我不知道你想要什麼。 – shihongzhi

回答

3

寫成生成器類:

import itertools 

class PhoneWords(object): 
    letters = { 
     2: 'abc', 
     3: 'def', 
     4: 'ghi', 
     5: 'jkl', 
     6: 'mno', 
     7: 'pqrs', 
     8: 'tuv', 
     9: 'wxyz' 
    } 

    def __init__(self, num_string): 
     self.num = [int(i) for i in num_string]     # => [3, 4] 
     self.chars = [PhoneWords.letters[i] for i in self.num] # -> ['def', 'ghi'] 

    def __iter__(self): 
     return (''.join(letters) for letters in itertools.product(*self.chars)) 

,並在使用中:

for word in PhoneWords("34"): 
    print word 

回報

dg 
dh 
di 
eg 
eh 
ei 
fg 
fh 
fi 
0

我想這是你想要的:

>>>from itertools import product 
>>>def permuteString(numString): 
>>> original = {2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} 
>>> #extract the wanted string, for example input numString='23', the pools is ['abc', 'def'] 
>>> pools = [original[int(n)] for n in numString]             
>>> return (''.join(x) for x in product(*pools)) #return a generator 

而且通過這種方式

>>>for x in permuteString('23'): 
>>> print x 
ad 
ae 
af 
bd 
be 
bf 
cd 
ce 
cf 

詳細使用:

產品Cartesian product of input iterables

發電機a simple and powerful tool for creating iterators

加入:是可以加入列表,例如:

x = ['a', 'b', 'c', 'd'] 
print ''.join(x) 

這將輸出:

'abcd' 
+0

好吧..只要我能理解它大聲笑 –

+0

它可以做到沒有'加入'和'池'?和id而不是返回作爲最終答案。並且非常感謝你,你這麼有用 –

+0

@ thebiggerchadder因爲'product'返回元組生成器。所以我們應該使用'join'來獲取'str'對象。'pool'只是一個臨時變量 – shihongzhi