如何用逗号分隔的字符串组成列表?

时间:2020-10-04 13:59:03

标签: python django

这里我有这样的字符串。

Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,

现在我想转换为这种格式

[{'Size': '20','color':'red'}, {'Size': '20','color': 'pink'}, {'Size': '90','color':'red'}, {'Size': ' 90','color': 'pink'}]

我们可以列出这样的列表吗?

2 个答案:

答案 0 :(得分:3)

import re

text = "Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,"

# Remove al whitespace
text = re.sub(r"\s+", "", text)

# Use named capture groups (?P<name>) to allow using groupdict
pattern = r"Size:(?P<Size>\d+),color:(?P<color>\w+)"

# Convert match objects to dicts in a list comprehension
result = [
    match.groupdict()
    for match in re.finditer(pattern, text)
]

print(result)

答案 1 :(得分:0)

另一种使用re.findall的解决方案,您可以获得字典列表

import re

my_string = 'Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,'
pattern = r'\s*?Size:(.*?),\s*?color:(.*?)(?:,|$)'

size_color_list = [{'Size': int(size), 'color': color.strip()}
                   for size, color in re.findall(pattern, my_string)]

print(size_color_list)

稍作修改即可将大小从字符串转换为整数。