python:元组列表中元组的链元素

时间:2013-12-03 07:46:19

标签: python

我想在字符串中找到元素的组合。 baseString的长度可变,例如'tbyhn'或'tg'等。

我试过了:

import itertools

baseString = 'tgby'
prd = [it for it in itertools.product(base,repeat=len(baseString)-1)]

prd是一个如下所示的列表:

[('t', 't', 't'), ('t', 't', 'g'), ('t', 't', 'b'), ..., ('y', 'y', 'y')]

我希望列表看起来像这样:

['ttt','ttg','ttb','tty','tgt',...,'yyy']

我该怎么做?

另外,如果我有一个像'prd'这样的元组列表,我怎么只链接每个元组中的元素。

修改

我不想要这些类型的结果:

   x = ['t','t','t','t','t','g','t','t','b','t','t','y',...,'y','y','y']

   x = ['tttttgttbttytgt...yyy']

1 个答案:

答案 0 :(得分:5)

只需像这样加入他们

bS = 'tgby'
prd = ["".join(it) for it in itertools.product(bS, repeat=len(bS)-1)]

编辑:@alko在评论

中建议的更快版本
prd = map(''.join, itertools.product(bS, repeat=len(bS)-1))