我正在尝试编写单词列表生成器。到目前为止,我已经成功实现了基本单词和数字的排列。
我需要帮助的问题是,我想将数字排列插入单词排列中。 (置换单词的字符串中有占位符char(“ +”)。)我也可以将字符串插入字符串中,并知道占位符的索引。问题不包括它们。
例如(成功部分):
permutatedwords = ["+me+you+", "+you+me+"]`
permutatednums = ["1", "2", "12", "21"]
所需的输出是(寻求帮助部分):
outList = ["1you1me1", "1you1me2", "1you2me1", "1you2me2", "2you1me1", "2you1me2", "2you2me1", "2you2me2"]
好吧,显然,我需要一个函数。
(我知道标题不太适合内容,因此可以随时对其进行修改。修改后,您可以删除此句子。)
答案 0 :(得分:0)
您可以使用itertools的groups_with_replacement生成合并的数字部分。然后将加号替换为每个组合中的每个数字:
permutatedwords = ["+me+you+", "+you+me+"]
permutatednums = ["1", "2", "12", "21"]
from itertools import combinations_with_replacement as combinationsR
wordsAndNums = [ (word,numbers) for word in permutatedwords for numbers in combinationsR(permutatednums,word.count("+")) ]
result = [ "".join(a+b for a,b in zip(word.split("+")+[""],nums)) for word,nums in wordsAndNums]
print(result)
['1me1you1', '1me1you2', '1me1you12', '1me1you21', '1me2you2',
'1me2you12', '1me2you21', '1me12you12', '1me12you21', '1me21you21',
'2me2you2', '2me2you12', '2me2you21', '2me12you12', '2me12you21',
'2me21you21', '12me12you12', '12me12you21', '12me21you21', '21me21you21',
'1you1me1', '1you1me2', '1you1me12', '1you1me21', '1you2me2', '1you2me12',
'1you2me21', '1you12me12', '1you12me21', '1you21me21', '2you2me2',
'2you2me12', '2you2me21', '2you12me12', '2you12me21', '2you21me21',
'12you12me12', '12you12me21', '12you21me21', '21you21me21']