Python:嵌套列表索引错误

时间:2017-07-04 18:04:32

标签: python nested-lists

result = []
for big in aisle:
  for small in big:
    if len(small) >= 0:
        result.append(small[1])
print(np.result)

我收到了这个错误:“字符串索引超出范围”

我在if语句中添加了以确保过道列表中的每个列表至少有2个项目,但仍然收到此错误。过道是一个包含列表的列表。目标是创建一个仅包含过道中每个列表中第二个项目的新列表。当然,使用numpy和数组更容易,但想学习......

2 个答案:

答案 0 :(得分:0)

len(small) >= 0始终为真 - 没有任何东西比<0>元素更少。要拥有索引为1的元素,small必须至少包含2个元素(small[0]small[1]),因此您应该测试len(small) > 1

答案 1 :(得分:-1)

Python列表索引是基于0的,我猜是小的可能只有一个项目。

result = []
for big in aisle:
  for small in big:
    if len(small) > 0: # >= 0 is always true
        result.append(small[0]) # Here if len(small) === 1 the item is at small[0]
print(result)