Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何拆分和删除列表中的字符串?_Python - Fatal编程技术网

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

Python 如何拆分和删除列表中的字符串?,python,Python,下面是我的示例代码: list1 = [{'name': 'foobar', 'parents': 'John Doe and Bartholomew Shoe'}, {'name': 'Wisteria Ravenclaw', 'parents': 'Douglas Lyphe and Jackson Pot' }] 我需要将父项拆分为一个列表,并删除“and”字符串。因此,输出应如下所示: list1 = [{'name': 'foobar', 'parents': ['

下面是我的示例代码:

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')

我不知道如何移动那个“,”字符串。

您应该在循环中使用
人,而不是迭代器本身

for people in list1:
    people['parents'] = people['parents'].split(' and ')
然后,当您打印
列表1
时,您会得到:

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

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

  • 如果某个名称碰巧包含该子字符串,则不会在
    上拆分
  • 删除
    周围的空白
像这样:

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)

对不起,我打错了。这就是我所做的,我得到的。列表1=[{'name':'foobar','parents':['johndoe,Bartholomew Shoe'],但我需要它像列表1=[{'name':'foobar','parents':['johndoe','Bartholomew Shoe'],@Nick,请再次查看输出。它与您需要的一样。我现在注意到了“and”。谢谢!谢谢您的输入!我还没有到达regex,但我会看看您的建议并了解它们。:)