首页 > 解决方案 > 使用 itertools [python] 将字符插入旧索引处的字符串

问题描述

我在字符串中删除空格。我交换字符串。

交换后,我想将旧索引处的空格放回原处。我想用itertools. 可能吗?

我使用 lambdas 的原因是因为我想按该顺序运行函数 n 次。我也想稍后在其他功能中使用它们。

我的代码如下所示:

import itertools
def func(n, strng):
    
    space_delete = lambda temp_var_strng: temp_var_strng.split(" ")
    join_char = lambda x: "".join(space_delete(x))
    swap_char = lambda s: "".join([join_char(s)[item-n] for item in range(len(join_char(s))) ])
    insert_space = lambda insert: list(itertools.chain.from_iterable(zip(itertools.repeat(" "), insert)))
    print(swap_char(strng))

如果我的输入是func(4, "hello world"),swap_char 应该在右边交换字符串 4 次。

swap_char给了我"orldhellow",所以如果我将所有空格放回旧索引中,它应该介于 orld 和 hellow 之间。

我的最后一个函数给了我这个输出

[' ', 'o', ' ', 'r', ' ', 'l', ' ', 'd', ' ', 'h', ' ', 'e', ' ', 'l', ' ', 'l', ' ', 'o', ' ', 'w']

但我的目标是得到:

["orld", " ", hellow]

如果我这样做一个嵌套循环,任务就解决了:

for o in lst:
        for i in o:
            result += s[cnt]
            cnt += 1
        result += " "

我可以在列表理解中实现这一点并使用它吗itertools?由于时间效率,我想采用解决方案。

提前致谢。

标签: pythonpython-3.xloopslambdaitertools

解决方案


你可以使用 numpy 来解决这个问题。

输入:字符串 = Hello World;n = 4;

预期输出:orldH ellow

Python 片段:

import numpy as np

# input
n = 4
string = list("Hello World")

string = np.array(string)

# Find the index of space char " "
space_index = np.where(string==' ')[0]

# Remove the space
string = np.delete(string, space_index)

# Rotate the string by n chars
string = np.concatenate((string[-(n):], string[:-(n)]))

# Add the space char to their original positions
string = np.insert(string, space_index, [' '])

print("".join(string))

推荐阅读