如何在多行字符串中找到为每组匹配字符创建单独的列表的方法

时间:2019-04-22 16:29:11

标签: python-2.7

为多行字符串中的每组匹配字符创建单独列表的最佳方法是什么?

str="""Name: abc1
Age: defg1
Place: xyz1

Name: abc2
Age: defg2
Place: xyz2

Name: abc3
Age: defg3
Place: xyz3
"""

使用以下代码,我可以创建一个大列表,但有兴趣创建三个单独的列表。

my_list = []
for each_module in str.split("\n"):
        if "Name: " in each_module:
                my_list.append(each_module.strip("Name: "))
        elif "Age: " in each_module:
                my_list.append(each_module.strip("Age: "))
        elif "Place: " in each_module:
                my_list.append(each_module.strip("Place: "))
print my_list

输出:

['abc1', 'defg1', 'xyz1', 'abc2', 'defg2', 'xyz2', 'abc3', 'defg3', 'xyz3']

首选输出:

['abc1', 'defg1', 'xyz1']
['abc2', 'defg2', 'xyz2']
['abc3', 'defg3', 'xyz3']

1 个答案:

答案 0 :(得分:0)

您入门很好,只需创建一个新列表,然后在填写地点时重置该列表,然后将其添加到主列表中即可,如下所示:

my_str="""Name: abc1
Age: defg1
Place: xyz1

Name: abc2
Age: defg2
Place: xyz2

Name: abc3
Age: defg3
Place: xyz3
"""
my_list = []
new_list = []
for each_module in my_str.split("\n"):
    if "Name: " in each_module:
        new_list.append(each_module.strip("Name: "))
    elif "Age: " in each_module:
        new_list.append(each_module.strip("Age: "))
    elif "Place: " in each_module:
        new_list.append(each_module.strip("Place: "))
        my_list.append(new_list)
        new_list = []
print(my_list)

输出:

[['bc1', 'defg1', 'xyz1'], ['bc2', 'defg2', 'xyz2'], ['bc3', 'defg3', 'xyz3']]