ooj*_*001 5 python string list
假设我有单词“apple”,字母集 ['a', 'l', 'e'] 和重复次数 3。据此我想创建以下集合: ['aaapple' 、“aaappllle”、“aaappllleee”、“appllle”、“appllleee”、“appleee”]。
这是我已经尝试过的:
l = ['a', 'l', 'e']
word = "apple"
for i in range(0, len(l)):
print wordWithDuplicatedLetters = "".join(3*c if c == l[i] else c for c in word)
Run Code Online (Sandbox Code Playgroud)
但这并不匹配所有组合,并且 itertools 似乎没有提供我正在寻找的可能性。
尝试使用这个循环:
s = ''
for i in word:
if i in l:
s += (3 * i)
else:
s += i
Run Code Online (Sandbox Code Playgroud)
这可以是列表理解:
s = ''.join([3 * i if i in l else i for i in word])
Run Code Online (Sandbox Code Playgroud)
现在在这两种情况下:
print(s)
Run Code Online (Sandbox Code Playgroud)
是:
aaappllleee
Run Code Online (Sandbox Code Playgroud)
完整回答您的问题
你必须使用:
import itertools
l = ['a', 'l', 'e']
word = 'apple'
l2 = []
for i in range(len(l)):
for x in itertools.combinations(l, r=i+1):
l2.append(x)
l3 = []
for lst in l2:
l3.append(''.join(char * 3 if char in lst else char for char in word))
print(l3)
Run Code Online (Sandbox Code Playgroud)
输出:
['aaapple', 'appllle', 'appleee', 'aaappllle', 'aaappleee', 'appllleee', 'aaappllleee']
Run Code Online (Sandbox Code Playgroud)