我使用try/except
块作为if/elif
的替代品,其中包含and
一堆try/except
。我正在查看列表并替换一些元素,如果它有x和x和x等。在我的项目中,我必须检查6件事情,这些事项让我使用.index()
和{{1}如果元素不存在,将抛出错误。
类比看起来像这样:
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
,所以我想知道这是否有明显的问题,或者这是否足够疯狂以至于其他开发人员会讨厌我它。
答案 0 :(得分:2)
那并不疯狂;尝试/除了非常pythonic - 请参阅this question以获得更多讨论。
另一种方法是:
if 'red' in colours and 'blue' in colours:
colour[colours.index('red')] = 'pink'
# etc
优于try / except:
尝试/除外的缺点:
contains
会自行搜索元素。除非你正在做一些要求它非常节省时间的事情,否则我会赞成可读性。但是,如果您有其他原因,那么try / except是不可原谅的。
答案 1 :(得分:2)
您可以使用set
。我们将分别使用issuperset
,difference_update
和update
,缩写为>=
,-=
和|=
:
colors = {'red', 'blue', 'yellow', 'orange'}
if colors >= {'red', 'blue'}:
colors -= {'red', 'blue'}
colors |= {'pink', 'light blue'}
elif colors >= {'yellow', 'purple'}:
colors -= {'yellow', 'purple'}
colors |= {'amarillo', 'lavender'}
答案 2 :(得分:1)
更新了答案
您可能希望使用map()构建一个函数,如下所示:
def replace(sequence, replaceDict):
for seekVal in replaceDict.keys():
if seekVal not in sequence:
return sequence #Not modified, as seek not found.
replaceFunc = lambda item: replaceVal if item==seekVal else item
for seekVal in replaceDict:
replaceVal = replaceDict[seekVal]
sequence = map(replaceFunc, sequence)
return sequence
然后运行:
colors = replace(colors, {'red' : 'pink', 'blue' : 'light blue'})
答案 3 :(得分:1)
您的代码很接近,但有一些有用的内置函数可以提供帮助:
colors = ['red', 'blue', 'yellow', 'orange']
if ('red' in colors and 'blue' in colors):
red_index = colors.index('red')
blue_index = colors.index('blue')
colors[red_index] = 'pink'
colors[blue_index] = 'light blue'
if ('yellow' in colors and 'purple' in colors):
yellow_index = colors.index('yellow')
purple_index = colors.index('purple')
colors[yellow_index] = 'amarillo'
colors[purple_index] = 'lavender'
这会创建逻辑门(两种颜色必须存在),以便只在您需要时执行。
这是一个非常小的变化,但我认为它会以更好的方式处理您的错误案例。
答案 4 :(得分:1)
您实际上可以使用dict
和列表理解更简单,更简短的方式:
colors = ['red', 'blue', 'yellow', 'orange']
# First define you replaces
replaces = {
'red': 'ping',
'blue': 'light blue',
'yellow': 'amarillo',
'purple': 'lavender'
}
# Then define the replacing function
def replace(key, replaces):
return replaces.get(key) or key
# And then replace all the intended element
colors = [replace(el, replaces) for el in colors]
那么这将做什么,对于每个元素,它将在dict中查找,如果它在dict中(即打算被替换),那么它将返回相应的替换,否则,它将返回原始值。
然后介绍你的条件,你可以这样:
if 'purple' in colors and 'red' in colors:
colors = [replace(el, {
'yellow': 'amarillo',
'purple': 'lavender'
}) for el in colors]
...
对于任何其他条件也一样。