【问题标题】:insert a character into a string at old index with itertools [python]使用 itertools [python] 将字符插入旧索引处的字符串
【发布时间】:2020-09-11 10:49:54
【问题描述】:

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

交换后,我想将旧索引处的空格放回原处。 我想通过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 解决方案。

提前致谢。

【问题讨论】:

  • “交换字符串”是什么意思?请提供示例输入和预期输出。
  • @buran 嗨,我做了这么多的编辑。 swap_char 函数正在做它应该做的事情。最后一个函数(insert_space)没有。
  • 将空格插入旧索引 (5),将得到 ["orldh", " ", "ellow"]。那么你的空间规则是什么?
  • 让我们说有一个字符串坐在“快速布朗狐狸跳过懒狗”。它不会只是一个索引。因此,应该在 [3, 9, 15, ...] 中插入一个空格,我可以使用 [ i for i in range(len(str)) of str[i] == ” ] 获得索引,但它是时间复杂性无效。
  • Itertools 并不比循环更省时...列表推导式本质上是循环。我认为您对性能的基本假设是有缺陷的。此外,您不应该将 lambda 表达式的结果分配给一个名称,这会破坏 它们的唯一目的,即匿名。官方风格建议是只使用完整的函数定义。

标签: python python-3.x loops lambda itertools


【解决方案1】:

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

输入:string = Hello World; n = 4;

预期输出:orldH elloW

Python sn-p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-16
    • 2011-04-30
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多