python - 删除列表列表中“”中的空格
问题描述
results = [[['2020 is the year', '29 year old "Samuel G"', '25 year old "John P Krul"', '40 year old "Trey Nunez S"', '22 year old "Fiona S Paul"', '50 year old "Sean J Beal"']]]
我尝试了以下操作,但这似乎摆脱了python3中“”中的中间词。
print([re.sub(r'"(\w+)(\s(\w+))*"', '"\\1\\3"', x.lower()) for x in results[0]])
我想要的输出是
results = [[['2020 is the year', '29 year old "samuelg"', '25 year old "johnpkrul"', '40 year old "treynunezs"', '22 year old "fionaspaul"', '50 year old "seanjbeal"']]]
仅删除 "" 和 "" 中的小写字母,以便 "John P Krul" 到 "johnpkrul",同时保持所有内容相同。
代码需要改什么?
解决方案
你可以试试这个。
def f(x): #Takes re.match object as input
a=x.group() #extractting the match
return a.replace(' ','').lower() #them to lower and removing spaces
[re.sub(r'\"([^"]*)\"',f,i) for i in results]
['2020 is the year',
'29 year old "samuelg"',
'25 year old "johnpkrul"',
'40 year old "treynunezs"',
'22 year old "fionaspaul"',
'50 year old "seanjbeal"']
编辑:对于列表列表
[[[re.sub(r'\"([^"]*)\"',f,i) for i in lst2] for lst2 in lst1] for lst1 in results]
输出:
[[['2020 is the year',
'29 year old "samuelg"',
'25 year old "johnpkrul"',
'40 year old "treynunezs"',
'22 year old "fionaspaul"',
'50 year old "seanjbeal"']]]
推荐阅读
- python - 如何在 JSON 数组 python 中访问 JSON 对象?
- vba - 无法在 VBA 中使用 Lapack DGETRF/DGETRI 反转矩阵
- swiftui - 如何预览依赖于 PresentationMode 的 SwiftUI 按钮?
- python - 如何使用 tkinter 事件“继续”或暂停不同的 while 循环?
- node.js - 即使在 knex.destroy() 之后,承诺仍然悬而未决
- javascript - 其他组件中的道具未定义 React
- unity3d - 当不再与玩家发生碰撞时,无法弄清楚如何阻止僵尸造成伤害
- python - BeautifulSoup 找不到标签
- python - 在参数描述之后有等号有什么意义
- bash - 如何在不使用 bash -x 的情况下将命令保存在变量中并在执行前打印翻译后的命令