繁体   English   中英

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

[英]How do I separate elements from a list of permutations of a string?

我想创建一个程序,它给出一个字符串的所有排列,然后从字符串列表中删除,并过滤掉以'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 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']
for i in range(0, len(x)):
    if x[i][0]=='o':
         y.append(x)
         print(y)

在此代码中,您将所有项目放在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(permutations('hello'))x=set(permutations('hello'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM