列表访问e [-1]很好,但e [1]不在Python中

时间:2014-04-14 10:58:29

标签: python

在Python中,我定义了

string = ("car-automobile, gem-jewel, journey-voyage, boy-lad, coast-shore, "
          "asylum-madhouse, magician-wizard, midday-noon, furnacestove, food-fruit, "
          "bird-cock, bird-crane, tool-implement, brother-monk, ladbrother, "
          "crane-implement, journey-car, monk-oracle, cemetery-woodland, foodrooster, "
          "coast-hill, forest-graveyard, shore-woodland, monk-slave, coast-forest, "
          "lad-wizard, chord-smile, glass-magician, rooster-voyage, "
          "noon-string".split(', '))
test = [i.split('-') for i in string]

并且以下代码导致错误:

[e[1] for e in test]
Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    [e[1] for e in test]
IndexError: list index out of range

但是代码可以运行

[e[-1] for e in test]

为什么会这样?

1 个答案:

答案 0 :(得分:6)

您有一些没有-的值:

>>> [e for e in string if not '-' in e]
['furnacestove', 'ladbrother', 'foodrooster']

当拆分时产生一个单元素列表;只有e[0],没有e[1]e[-1]始终为您提供最后一个元素,即使只有1个。

相关问题