【问题标题】:python 2.7 permutation of string starting from indexpython 2.7从索引开始的字符串排列
【发布时间】:2014-01-21 00:23:48
【问题描述】:

我想在python中对字符串进行排列:

 string= asis:abc
    permutations = ["".join(x) for x in permutations(string,len(string))] 
        print permutations

但是我需要在这个例子之后开始:即我想获得这样的东西:

asis:abc, asis:acb, asis:bca, asis:bac, ...

我该怎么做?

【问题讨论】:

  • permutations = ...permutations(...) 这是个坏主意。你把函数名吹走了。

标签: python string python-2.7 indexing permutation


【解决方案1】:

应该这样做:

from itertools import permutations

s = 'asis:abc'
delimiter = ':'
pre, post = s.split(delimiter)
for p in permutations(post):
    print '{}{}{}'.format(pre, delimiter, ''.join(p))

输出:

asis:abc
asis:acb
asis:bac
asis:bca
asis:cab
asis:cba

或者您可以通过将 for 循环替换为列表推导来将值存储在列表中:

perms = ['{}{}{}'.format(pre, delimiter, ''.join(p)) for p in permutations(post)]

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    相关资源
    最近更新 更多