我正在使用
类比如下:
所以,如果
我对这种方法有点担心,因为它似乎滥用了
try/except
块来代替一堆and
的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
,所以我想知道是否存在明显的问题,或者这是否足够疯狂,使其它开发人员会厌恶我。
len(set(colors) & set("purple yellow".split())) == 2
- Joran Beasleyif ('red' in colors and 'blue' in colors):
而不是try:
应该能够满足你的所有需求。 - Alea Kootz