将一个字符串与多个列表/数组转换为单独的列表
标题真糟糕。让我来解释一下。我正在使用Wolfram|Alpha的API。在解析它的时候,我得到了这些让人头疼的字符串,比如查询“蜘蛛侠”时得到的:
"year | title | medium 1962 | Amazing Fantasy #15 | comic book 1967 | Spider-Man | animation > 1977 | The Amazing Spider-Man | television 1978 | Questprobe #2 Spider-Man | video game 2002 > | Spider-Man | movie"
实际上,这个字符串应该是像下面这样的列表:
[year, title, medium]
[1962, Amazing Fantasy #15, comic book]
[1967, Spider-Man, video game]
[2002, Spider-Man, movie]
我可以很容易地把这个字符串拆分成一个大列表……但是我想不出一个简单的方法把它们整理成应该的列表(如上所示)。除了把它转换成一个大列表,然后解析这个列表,按每三个项目创建一个新列表的方式,还有什么建议吗……?
我想法的例子(比较麻烦的方式):
listA = list()
listA = textRepresentation.split("|")
listB = list()
listC = list()
i = 1
for item in listA:
if(i == 3):
listB.append(listC)
i = 1
else:
listC.append(item)
i++
1 个回答
2
import re
zip(*[(i.strip() for i in re.split('(\d{4})|\||>', text) if i and i.strip())]*3)
输出:
[('year', 'title', 'medium'),
('1962', 'Amazing Fantasy #15', 'comic book'),
('1967', 'Spider-Man', 'animation'),
('1977', 'The Amazing Spider-Man', 'television'),
('1978', 'Questprobe #2 Spider-Man', 'video game'),
('2002', 'Spider-Man', 'movie')]