python - 列表访问 e[-1] 可以,但 e[1] 不在 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, 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]

为什么会这样?

最佳答案

你有一些没有 - 的值:

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

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

关于python - 列表访问 e[-1] 可以,但 e[1] 不在 Python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23058346/

相关文章:

python - 有什么办法可以延长请求超时限制?

python - python AI 的数据集预处理

python - 如何在 wordpress 博客中编写 python 代码?

python - 数据透视表的 Pandas 反转

python - 如何使用python在mapreduce中的直方图(Graph)中获取结果?

python - django - 迁移和模型转换的问题

python - 如何使用python脚本检查elasticsearch中是否存在索引并对其执行异常处理?

python - readinto() 替换?

python - 如何显示每个用户对用户对话的最后一条消息以保留聊天记录?

python - 如何检查模块是否可用于导入?