2016-12-14 84 views
1

我正在使用Python 2.7。我試圖創建一個函數,它可以將字符串壓縮成一個更大的字符串,從一個任意索引開始並以任意的步驟開始。在任意索引和步驟(Python)下將字符串壓縮在一起

例如,我可能希望將串@#*#*壓縮到更大的串TNAXHAXMKQWGZESEJFPYDMYP起始於5 字符與3步驟所得到的字符串應該是:

[email protected]#QW*GZ#ES*EJFPYDMYP 

工作功能我想出來的是

#Insert one character of string every nth position starting after ith position of text 

text="TNAXHAXMKQWGZESEJFPYDMYP" 

def zip_in(string,text,i,n): 
    text=list(text) 
    for c in string: 
     text.insert(i+n-1,c) 
     i +=n 
    text = ''.join(text) 
    print text 

這個函數產生所需的結果,但我覺得它不像它可能是優雅的。

此外,我希望它足夠一般,我可以向後拉一個字符串,也就是說,從文本的位置開始,我想將字符串插入到一個字符中時間倒退。

例如,我可能希望將串@#*#*壓縮到更大的串TNAXHAXMKQWGZESEJFPYDMYP起始於具有-3的步驟的22次位置。結果字符串應該是:

TNAXHAXMKQW*GZ#ES*EJ#[email protected] 

從我目前的功能,我可以通過設置ň負做到這一點,但是如果我想的-3一步,我需要設置ň爲-2。

所有這一切都使我對我的問題:

是否有一個更優雅(或Python化)的方式來實現我的目的?


這裏是不提供一個籠統的回答一些相關的問題:

Pythonic way to insert every 2 elements in a string
Insert element in Python list after every nth element
Merge Two strings Together at N & X

回答

0

你可以使用一些功能從itertoolsmore_itertools庫(使一定要有他們),並結合他們得到你的結果:chunkedizip_longest

# Parameters 
s1 = 'ABCDEFGHIJKLMNOPQ' # your string 
s2 = '@#@#' # your string of elements to add 
int_from = 4 # position from which we start adding letters 
step = 2 # we will add in elements of s2 each 2 letters 

return_list = list(s1)[:int_from] # keep the first int_from elements unchanged 
for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''): 
    return_list.extend(letter) 
    return_list.append(char) 

然後讓你的字符串返回做:

''.join(return_list) 

輸出:

# For the parameters above the output is : 
>> '[email protected]#[email protected]#MNOPQ' 

什麼izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue='')回報?

for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''): 
    print(letter, char) 

>> Output 
>> (['E', 'F'], '@') 
    (['G', 'H'], '#') 
    (['I', 'J'], '@') 
    (['K', 'L'], '#') 
    (['M', 'N'], '') 
    (['O', 'P'], '') 
    (['Q'], '')