python - 如何在字符串列表中的括号之间连接字符串
问题描述
poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values
是否可以合并以开头'('
和结尾的字符串,')'
然后将其重新插入到同一个列表或新列表中?
我想要的输出poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]
解决方案
您可以迭代列表元素,检查每个元素是否以 开头(
或结尾)
。找到括号之间的元素后,可以通过 string.join
方法将它们连接起来,如下所示:
poke_list = ['Charizard', '(Mega', 'Charizard', 'X)', '78', '130']
new_poke_list = []
to_concatenate = []
flag = 0
for item in poke_list:
if item.startswith('(') and not item.endswith(')'):
to_concatenate.append(item)
flag = 1
elif item.endswith(')') and not item.startswith('('):
to_concatenate.append(item)
concatenated = ' '.join(to_concatenate)
new_poke_list.append(concatenated)
to_concatenate = []
flag = 0
elif item.startswith('(') and item.endswith(')'):
new_poke_list.append(item)
else:
if flag == 0:
new_poke_list.append(item)
else:
to_concatenate.append(item)
print(new_poke_list)
flag
设置为当1
元素在括号内时,0
否则,您可以管理所有情况。
推荐阅读
- reactjs - 无法访问 React 的渲染方法中的属性
- c# - 保存网站寿命短的全球唯一代币?
- python - 无法从 MongoDB 中提取信息
- java - Jersey REST-Client WebTarget - 找不到内容类型的 MessageBodyReader
- reactjs - 嵌套对象的状态更新方法问题
- soap - 使用 PHP 连接到受 WS-Security 保护的 Soap Web 服务
- r - 数字预测器的逻辑回归?
- c# - C# SerialPort.Write 偶尔会因“请求的资源正在使用中”而失败
- php - 带有语言环境的 laravel 功能测试
- c - 使用 Visual Studio 2019 中的 microsoft cl.exe 具有 64 位目标的 sigset_t