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

时间:2017-02-21 11:20:46

标签: 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)

我用这段代码试了一下,但它给了我很长的清单。

2 个答案:

答案 0 :(得分:3)

在构建完整列表之前,您可以过滤掉那些不以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

tuple再次将排列转换为整个字符串。如果您想要string的{​​{1}},请将其删除。

为了提高效率,您只需从'o'移除'hello',然后将其添加到'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']

答案 1 :(得分:0)

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'))