IndexError:列表索引超出范围python 3.4

时间:2016-08-22 09:16:36

标签: python python-3.x lambda

尝试运行此代码:

sorted_by_name = sorted(sort_array,key=lambda x:x[0]))

我明白了:

  

IndexError:列表索引超出范围

如何解决此问题?

由于

2 个答案:

答案 0 :(得分:1)

sort_array = ['abc', 'acd', 'abcd', ''] sort_array ['abc', 'acd', 'abcd', ''] sorted(sort_array, key=lambda student: student[0]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> IndexError: string index out of range 中的一个元素应该是空的或空字符串。见下面的例子

示例#1:

sorted_by_name

例如#2,我将sort_array作为列表​​列表,与您的>>> student_tuples = [ ... ['john', 'A', 15], ... [] ... ] >>> sorted_by_name = sorted(student_tuples,key=lambda x:x[0]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> IndexError: list index out of range

示例更匹配
sort_array

因此,我要求您检查输入ui-grid header一次,如果它有任何空列表

答案 1 :(得分:0)

这意味着列表中至少有一件事是空的,所以没有第一个元素。修复很简单,不要传递密钥:

np.exp(a)

a的默认实现已尝试第一项,然后是第二项,第三项等。当您传递一个键时,它首先尝试您的键,即第一项。如果它发现两个是相同的,它会自己检查。它检查第一个项目(再次),第二个项目,第三个项目等。换句话说,两者都是相同的,除了提供一个键可能意味着第一个项目被检查两次,当然默认实现没有&# 39;空列表中的错误。