列表访问e[-1]可以,但e[1]不是Python中的

列表访问e[-1]可以,但e[1]不是Python中的,python,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, ladbroth

在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 for e in string if not '-' in e]
['furnacestove', 'ladbrother', 'foodrooster']
拆分后,将生成一个元素列表;只有
e[0]
,没有
e[1]
e[-1]
始终为您提供最后一个元素,即使只有1个

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