[英]How to make a list with a comma separated strings?
Here I have string like this.在这里,我有这样的字符串。
Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink,
Now I want to convert into this format现在我想转换成这种格式
[{'Size': '20','color':'red'}, {'Size': '20','color': 'pink'}, {'Size': '90','color':'red'}, {'Size': ' 90','color': 'pink'}]
Can we make a list like this ?我们可以列一个这样的清单吗?
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)
Another solution using re.findall
you can get the list of dicts使用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)
Slightly modified converting the size from a string to an int.稍微修改将大小从字符串转换为整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.