python - 使用 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
?由于时间效率,我想采用解决方案。
提前致谢。
解决方案
你可以使用 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))
推荐阅读
- python - 用python最大化对数似然函数
- html - 如何让悬停下划线出现在文本上方并具有阴影效果?
- vue.js - flatpickr.js 可以在开发中使用,但不能在使用 Vue.js 的生产中使用
- .net - 来自 .NET Windows 服务 .config 文件中的“不那么特殊”字符的错误
- javascript - npm run dev 和 parcel index.html 的区别
- react-native - 如何在展会上更改 MIUI 强制暗模式?
- c++ - 使用标题的问题
在 C++ 中 - json - 如何在 Dart/Flutter 中解码嵌套的 JSON 对象列表
- java - Java SQL,一般错误 org.hsqldb.HsqlException
- c++ - 如何使用 Visual Studio 2019 [C++] [SFML] 编译独立的 exe