鉴于此词典
dictt={2:'abc',3:'def',4:'gfi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}
我需要做一个自定义排列。
输入中的数字将告诉您输出的时间长度。
输入也将指向被置换的字母。
例如,。 “34”将使程序返回第一个序列的第一个字母,并逐个添加第二个序列的所有3个字母。
a + d = ad a + e = ae a + d = af
然后它将取第一个序列的第二个字母并添加第二个序列的所有3个字母
b + d = bd b + e = be b + f = bf
然后是第三封信
c + d = cd c + e = ce c + f = cf
因此,当你输入34时,它将返回ad af af bd cd b cf cf
如果输入是3个数字。然后输出将是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 :(得分: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
答案 1 :(得分: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'