首页 > 解决方案 > List 和 Tuple 中相同操作的不同 ValueError

问题描述

当我尝试获取索引时,我很好奇为什么 List 和 Tuple 中的 ValueErrors 不同。列表的 ValueError 以良好的格式返回,实际参数“ValueError:'ITEM'不在列表中”,而元组返回类似“ValueError:tuple.index(x):x 不在元组中”的内容。我认为 List 和 Tuple 都在调用相同的 index() 方法,那么为什么它会引发不同的 ValueErrors?


>>> jframe_li
['Angular', 'React', 'Vue.js', 'Ember.js', 'Mereor', 'Node.js', 'Backbone.js']
>>> jframe_tu
('Angular', 'React', 'Vue.js', 'Ember.js', 'Mereor', 'Node.js', 'Backbone.js')
>>> jframe_li.index('React')
1
>>> jframe_tu.index('React')
1
>>> jframe_li.index('react')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'react' is not in list

>>> jframe_tu.index('react')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple

标签: pythonpython-3.xlisttuples

解决方案


index列表和元组的方法存在实现差异,包括 raise 的文本ValueError

请参阅tuple.index 的ValueError字符串和 list.index 的 ValueError 字符串


推荐阅读