我正在使用 try/except
block 来替代 if/elif
,它有一堆 和
。我正在查看一个列表并替换一些元素,如果它有 x 和 x 和 x 等。在我的项目中,我必须检查 6 个以上的东西,这些东西吸引我使用 try/except
使用 .index()
如果元素不存在将抛出错误。
类比如下:
colors = ['red', 'blue', 'yellow', 'orange']
try:
red_index = colors.index('red')
blue_index = colors.index('blue')
colors[red_index] = 'pink'
colors[blue_index] = 'light blue'
except ValueError:
pass
try:
yellow_index = colors.index('yellow')
purple_index = colors.index('purple')
colors[yellow_index] = 'amarillo'
colors[purple_index] = 'lavender'
except ValueError:
pass
因此,如果 colors
数组不包含 'purple'
以及 'yellow'
,我不想要该数组改变。
我对这种方法有点警惕,因为它似乎是在滥用 try/except
。但它比替代方案短得多,因为无论如何我都必须获取元素的 index
,所以我想知道这是否存在明显的问题,或者这是否足够疯狂以至于其他开发人员会为此恨我。
最佳答案
这并不疯狂; try/except 非常 pythonic - 参见 this question进行更多讨论。
另一种方法是:
if 'red' in colours and 'blue' in colours:
colour[colours.index('red')] = 'pink'
# etc
与 try/except 相比的优势:
- 更少的代码行,如果你喜欢的话
- 更具可读性——任何 future 的读者都会立即明白你的意思
与 try/except 相比的缺点:
- 由于
contains
将自己搜索元素,因此速度较慢(尽管速度完全可以忽略不计)。
除非您正在做的事情要求它非常节省时间,否则我更喜欢可读性。但是,如果您有其他原因,try/except 并不是不可原谅的。
关于python - 检查特定元素列表的更好方法 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854086/