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

Python 如何从字符串的排列列表中分离元素?,python,string,python-3.x,permutation,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'
开头的字符串。我想找到所有以
'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
开头的代码(如果…[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
s的
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']
在这段代码中,您每次都将x列表中的所有项(表示所有排列)放入y列表中。这就是为什么你有一个长长的清单

试试这个代码

from itertools import permutations
x=list(permutations('hello'))
y=[]
for i in x:
    if i[0]=='o':
        y.append(i)
print(y)
如果您想获得唯一列表,只需更改

x=list(排列('hello'))
to
x=set(排列('hello'))

from itertools import permutations
x=list(permutations('hello'))
y=[]
for i in x:
    if i[0]=='o':
        y.append(i)
print(y)