相关疑难解决方法(0)

检查特定元素列表的更好方法 - python

我使用try/except块作为替代if/elif,有一堆ands.我正在寻找一个列表,并替换一些元素,如果它有x和x和x等.在我的项目中,我必须检查6个东西,这些吸引我使用try/exceptwith .index()将导致错误,如果元素isn不存在.

类比看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

因此,如果colors数组不包含'purple'还有'yellow',我不希望阵列,以改变.

我对这种方法有点警惕,因为它似乎是滥用try/except.但是它比替代方案要短得多,因为index无论如何我都必须抓住元素,所以我想知道这是否存在明显的问题,或者这是否足够疯狂以至于其他开发人员会讨厌它.

python if-statement try-except

6
推荐指数
1
解决办法
123
查看次数

有没有另一种方法在python生成器上调用next?

我有一个发电机,我想知道我是否可以使用它而不必担心StopIteration,我想在没有它的情况下使用它for item in generator.我想将它与while语句(或其他构造)一起使用.我怎么能这样做?

python language-features

3
推荐指数
1
解决办法
1360
查看次数