我想创建一个程序,给出字符串的所有排列,然后从字符串列表中过滤出以 'o'
开头的字符串。我想找到以 'o'
开头的所有排列。
from itertools import permutations
x = list(permutations('hello'))
y = []
for i in range(0, len(x)):
if x[i][0] == 'o':
y.append(x)
print(y)
我用这段代码尝试过,但它给了我一个很长的列表。
最佳答案
在构建完整的之前,您可以过滤掉那些不以 o
开头的内容(if ...[0] == 'o'
部分)列表:
>>> y = [''.join(perm) for perm in permutations('hello') if perm[0] == 'o']
>>> y
['ohell', 'ohell', 'ohlel', 'ohlle', 'ohlel', 'ohlle', 'oehll', 'oehll',
'oelhl', 'oellh', 'oelhl', 'oellh', 'olhel', 'olhle', 'olehl', 'olelh',
'ollhe', 'olleh', 'olhel', 'olhle', 'olehl', 'olelh', 'ollhe', 'olleh']
str.join
再次将排列转换为整个字符串。如果您希望将其作为 string
的 tuple
,请将其删除。
为了提高效率,您只需从 'hello'
中删除 'o'
并将其添加到 'hell'
的每个排列之前即可得到相同的排列:
>>> ['o{}'.format(''.join(perm)) for perm in permutations('hell')]
['ohell', 'ohell', 'ohlel', 'ohlle', 'ohlel', 'ohlle', 'oehll', 'oehll',
'oelhl', 'oellh', 'oelhl', 'oellh', 'olhel', 'olhle', 'olehl', 'olelh',
'ollhe', 'olleh', 'olhel', 'olhle', 'olehl', 'olelh', 'ollhe', 'olleh']
关于python - 如何从字符串的排列列表中分离元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42365880/