这是我的示例代码:
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')
我不确定如何移动','字符串。
答案 0 :(得分:1)
您应该在循环内使用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']}]
答案 1 :(得分:0)
扩展其他人说的话:您可能想对正则表达式进行拆分,以便于
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)