python - 如何从字符串的排列列表中分离元素?

标签 python string python-3.x permutation

我想创建一个程序,给出字符串的所有排列,然后从字符串列表中过滤出以 '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 再次将排列转换为整个字符串。如果您希望将其作为 stringtuple,请将其删除。

<小时/>

为了提高效率,您只需从 '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/

相关文章:

c - 发现数组中的任何值是否与给定值匹配

python-3.x - "ImportError: cannot import name ' convert_from_path ' from partially initialized module ' pdf2image ' (most likely due to a circular import)"

python - 在 Python 的 try 语句中检查的 if 语句,需要执行代码以防出现异常

java - 如何在 Java 中比较字符串?

c++ - 我可以使用 SIMD 来加速字符串操作吗?

python - 将 Pandas 数据框从宽转换为长

python - 如何很好地处理 [ :-0] slicing?

python - 如何自动在 Python 函数中设置 "input"?

python - python3.4 的 SciPy 和 ggplot 安装

Python Tkinter Canvas 获取线的基本方向