gpt4 book ai didi

python - 字符的组合和排列

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:57 24 4
gpt4 key购买 nike

我正在尝试编写优雅的代码,从单个字符创建字符组合/排列:

例如从单个字符我想要代码来创建这些排列(结果的顺序并不重要):

'a' ---->  ['a', 'aa', 'A', 'AA', 'aA', 'Aa']

到目前为止我所拥有的不太优雅的解决方案:

# this does it...
from itertools import permutations
char = 'a'
p = [char, char*2, char.upper(), char.upper()*2]
pp = [] # stores the final list of permutations
for j in range(1,3):
for i in permutations(p,j):
p2 = ''.join(i)
if len(p2) < 3:
pp.append(p2)
print pp
['a', 'aa', 'A', 'AA', 'aA', 'Aa']

#this also works...
char = 'a'
p = ['', char, char*2, char.upper(), char.upper()*2]
pp = [] # stores the final list of permutations
for i in permutations(p,2):
j = ''.join(i)
if len(j) < 3:
pp.append(j)
print list(set(pp))
['a', 'aa', 'aA', 'AA', 'Aa', 'A']

# and finally... so does this:
char = 'a'
p = ['', char, char.upper()]
pp = [] # stores the final list of permutations
for i in permutations(p,2):
pp.append(''.join(i))
print list(set(pp)) + [char*2, char.upper()*2]
['a', 'A', 'aA', 'Aa', 'aa', 'AA']

我不太擅长 lambda,我怀疑这可能是更好的解决方案。

那么,你能帮我找到最优雅/Pythonic 的方式来达到所需的结果吗?

最佳答案

您可以简单地使用itertools.product使用不同的repeat值来获得预期的结果

>>> pop = ['a', 'A']
>>> from itertools import product
>>> [''.join(item) for i in range(len(pop)) for item in product(pop, repeat=i + 1)]
['a', 'A', 'aa', 'aA', 'Aa', 'AA']

关于python - 字符的组合和排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40336831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com