如何基于python中的字符串从列表中创建子列表? [英] How can I make sublists from a list based on strings in python?
本文介绍了如何基于python中的字符串从列表中创建子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
['<text id="32a45" language="ENG" date="2017-01-01" time="11:00" timezone="Eastern">',
'<text id="32a47" language="ENG" date="2017-01-05" time="1:00" timezone="Central">',
'<text id="32a48" language="ENG" date="2017-01-07" time="3:00" timezone="Pacific">']
由此,我想创建如下子列表:
From this I want to make sublists like:
id = ["32a45", "32a47", "32a48"]
date=["2017-01-01", "2017-01-05", "2017-01-07"]
我该怎么做?
谢谢.
This was the original question It is a broken xml file and tags are messed up, hence I cannot use xmltree. So I am trying something else.
推荐答案
使用re.search()
函数的简单解决方案:
Simple solution using re.search()
function:
import re
l = ['<text id="32a45" language="ENG" date="2017-01-01" time="11:00" timezone="Eastern">',
'<text id="32a47" language="ENG" date="2017-01-05" time="1:00" timezone="Central">',
'<text id="32a48" language="ENG" date="2017-01-07" time="3:00" timezone="Pacific">']
ids, dates = [], []
for i in l:
ids.append(re.search(r'id="([^"]+)"', i).group(1))
dates.append(re.search(r'date="([^"]+)"', i).group(1))
print(ids) # ['32a45', '32a47', '32a48']
print(dates) # ['2017-01-01', '2017-01-05', '2017-01-07']
这篇关于如何基于python中的字符串从列表中创建子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文