在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[0]
,没有e[1]
。e[-1]
总是给出最后一个元素,即使只有1个。你知道吗相关问题 更多 >
编程相关推荐