2016-11-10 89 views
0

我有一个嵌套列表main_category,每个嵌套列表是一个unicode字符串的商业名称。嵌套表的前五行低于:Python列表索引超出范围嵌套列表

[[u'Medical Centers', u'Health and Medical'], 
[u'Massage', u'Beauty and Spas'], 
[u'Tattoo', u'Beauty and Spas'], 
[u'Music & DVDs', u'Books, Mags, Music and Video', u'Shopping'], 
[u'Food', u'Coffee & Tea']] 

所以我想每个列表的第一个元素,我已经试过列表理解,拉链,但没有任何工程。

new_cate = [d[0] for d in main_category] 
lst = zip(*main_category)[0] 

但他们都给予我

IndexErrorTraceback (most recent call last) 
<ipython-input-49-4a397c8e62fd> in <module>() 
----> 1 lst = zip(*main_category)[0] 
IndexError: list index out of range 

我真的不知道什么是错。那么谁能帮忙?非常感谢!

+0

你能确认你执行的代码? [医学中心],'按摩','纹身','音乐和DVD','食物']和('医疗中心','按摩','纹身','音乐&DVDs','Food') –

+0

您的完整列表包含一个空子列表'[]'在某处。确认。 –

+1

[在python中提取每个子列表的第一项可能的重复](http://stackoverflow.com/questions/25050311/extract-first-item-of-each-sublist-in-python) –

回答

0

的错误表示一个/一些完整列表子列表是空的列表。你需要妥善处理。你可以把一个三元操作列表中的理解来替代默认值时,该列表是空和索引的第一个项目时,它不是:

default = '' 
new_cate = [d[0] if d else default for d in main_category] 
#    ^^^^-> test if list is truthy 

您也可以通过复制此修复程序zip这是itertools变种izip_longest它允许你设置一个fillvalue

from itertools import izip_longest 

default = '' 
lst = list(izip_longest(*main_category, fillvalue=default))[0] 
+0

没错。三元操作符正在帮助!非常感谢。 – Parker

-1

所以你有一个列表清单。

for content in matrix: 

在每次迭代content将返回一个完整的列表。例如[u'Medical Centers', u'Health and Medical']

如果你print(content[0]),你会得到当前列表的第一个值,这将是u'Medical Centers'

如果有没有在matrix内容的列表,print(content[0])将提高IndexError,所以你需要检查当前列表不是Noneif content:


matrix = [[u'Medical Centers', u'Health and Medical'], 
[u'Massage', u'Beauty and Spas'], 
[u'Tattoo', u'Beauty and Spas'], 
[u'Music & DVDs', u'Books, Mags, Music and Video', u'Shopping'], 
[u'Food', u'Coffee & Tea']] 

for content in matrix: 
    if content: 
     print(content[0]) 

>>> Medical Centers 
>>> Massage 
>>> Tattoo 
>>> Music & DVDs 
>>> Food 
+0

这不适用于整个列表 – Parker

+0

请问您可以在代码中添加一些上下文吗? – ppperry

+0

完成。它以前不会用于@Parker,因为我没有检查“空列表”,但我现在修复了这个问题。 –