如何拆分和删除列表中的字符串?

2024-10-05 10:55:19 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的示例代码:

list1 = [{'name': 'foobar', 'parents': 'John Doe and Bartholomew Shoe'},
     {'name': 'Wisteria Ravenclaw', 'parents': 'Douglas Lyphe and Jackson Pot'
    }]

我需要将父级拆分为一个列表并删除'and'字符串。所以输出应该是这样的:

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'Bartholomew Shoe'],
     {'name': 'Wisteria Ravenclaw', 'parents': ['Douglal Lyphe', 'Jackson', 'Pot']
    }]

请帮我弄清楚。你知道吗

for people in list1:
    people['parents'] = people['parents'].split('and')

我不知道怎么移动那根绳子。你知道吗


Tags: andnamejohnpeoplefoobardoepotjackson
2条回答

扩展其他人所说的:您可能希望在正则表达式上拆分,以便

  • 如果一个名称恰好包含了这个子字符串,就不能在and上拆分
  • 删除and周围的空白。你知道吗

像这样:

import re

list1 = [
  {'name': 'foobar', 'parents': 'John Doe and Bartholomew Shoe'},
  {'name': 'Wisteria Ravenclaw', 'parents': 'Douglas Lyphe and Jackson Pot'}
]

for people in list1:
    people['parents'] = re.split(r'\s+and\s+', people['parents'])

print(list1)

应该在循环中使用people,而不是迭代器本身。你知道吗

for people in list1:
    people['parents'] = people['parents'].split(' and ')

当你打印list1时,你会得到:

[{'name': 'foobar', 'parents': ['John Doe', 'Bartholomew Shoe']}, {'name': 'Wisteria Ravenclaw', 'parents': ['Douglas Lyphe', 'Jackson Pot']}]

相关问题 更多 >

    热门问题