单词合并
我是新的用户学习Python。我有查询是否可以完成。如果用户输入一个单词假设“ dance”和字符是“ $”和“@”,则他将获得所有单词和字符组合的可能性['d $@a $@a $@n@$ c@$ e',, d@$ a@$ n@$ c@$ e,'da $ n $ c $ e','d $@an $ c@$ e','da@nc $ e']等。组合。有可能实现吗?
import itertools as it
string = 'ABCD' # input('enter string: ')
fill_char = '$' # input('enter fill_char: ')
fillers = it.product(['', fill_char], repeat=len(string))
for filler in fillers:
tmp = it.zip_longest(string, filler)
print(''.join([''.join(char_and_fill_char) for char_and_fill_char in tmp]))
Output:
ABCD
ABCD$
ABC$D
ABC$D$
AB$CD
AB$CD$
AB$C$D
AB$C$D$
A$BCD
A$BCD$
A$BC$D
A$BC$D$
A$B$CD
A$B$CD$
A$B$C$D
A$B$C$D$
我想要3个字符的组合。如果有人能提供帮助,我会非常奇怪。
I am new user learning python. I have query if it can be done or not. If user input a word suppose "Dance" and characters are "$" and "@", he would get a all possibilities of word and character combination for example ['D$@a$@n@$c@$e',D@$a@$n@$c@$e, 'Da$n$c$e', 'D$@an$c@$e', 'Da@nc$e'], etc. It should give a combinations. Is it possible to achieve?
import itertools as it
string = 'ABCD' # input('enter string: ')
fill_char = '
I wanted combination of 3 characters. If anybody could help I would be very greatful.
# input('enter fill_char: ')
fillers = it.product(['', fill_char], repeat=len(string))
for filler in fillers:
tmp = it.zip_longest(string, filler)
print(''.join([''.join(char_and_fill_char) for char_and_fill_char in tmp]))
Output:
ABCD
ABCD$
ABC$D
ABC$D$
AB$CD
AB$CD$
AB$C$D
AB$C$D$
A$BCD
A$BCD$
A$BC$D
A$BC$D$
A$B$CD
A$B$CD$
A$B$C$D
A$B$C$D$
I wanted combination of 3 characters. If anybody could help I would be very greatful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个可能的解决方案:
对于更清晰的演示,我只选择了两个字母。基本上,将您的
字符串
的每个字母拿走,然后将fill_chars
的所有可能组合加入其中。然后构建所有列表的产品(每个列表都包含一个字母的所有组合)。添加了几个评论和打印语句以进行解释。
Here is one possible solution:
For more clear presentation I only chose a string of two letters. Basically take every single letter of your
string
and join all possible combinations offill_chars
to it. Then build the product of all lists (each containing all combinations for one letter).Added several comments and print statements for explanation.