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

2024-06-16 14:05:06 发布

您现在位置: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]

为什么会这样?你知道吗


Tags: intestforstringcarwizardmonknoon
1条回答
网友
1楼 · 发布于 2024-06-16 14:05:06

有几个值中没有-

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

当拆分时,结果是一个单元素列表;只有e[0],没有e[1]e[-1]总是给出最后一个元素,即使只有1个。你知道吗

相关问题 更多 >