【问题标题】:Zipping strings together at arbitrary index and step (Python)以任意索引和步骤将字符串压缩在一起(Python)
【发布时间】:2017-04-30 02:16:41
【问题描述】:

我正在使用 Python 2.7。我正在尝试创建一个函数,该函数可以将一个字符串压缩成一个更大的字符串,该字符串从任意索引开始并具有任意步骤。

例如,我可能想将字符串 @#*#* 压缩到较大的字符串 TNAXHAXMKQWGZESEJFPYDMYP,从第 5th 个字符开始,步长为 3。生成的字符串应该是:

TNAXHAX@MK#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

这个函数产生了想要的结果,但我觉得它没有它应该的那么优雅。

此外,我希望它足够通用,可以向后压缩字符串,即从文本的第 ith 位置开始,我想将字符串插入一次一个字符,后退一步。

例如,我可能希望将字符串 @#*#* 压缩到较大的字符串 TNAXHAXMKQWGZESEJFPYDMYP 中,从第 22nd 位置开始,步长为 -3。结果字符串应该是:

TNAXHAXMKQW*GZ#ES*EJ#FP@YDMYP

使用我当前的函数,我可以通过将 n 设置为负数来做到这一点,但如果我想要 -3 的步长,我需要将 n 设置为 -2。

所有这些都引出了我的问题:

有没有更优雅(或 Pythonic)的方式来达到我的目的?


以下是一些不提供一般答案的相关问题:

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

【问题讨论】:

    标签: string python-2.7


    【解决方案1】:

    您可以使用 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 :
    >> 'ABCDEF@GH#IJ@KL#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'], '')
    

    【讨论】:

      猜你喜欢
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2015-05-28
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      相关资源
      最近更新 更多