格式化条件语句的最佳方式
Best way to format conditionnal statement
我有以下条件语句:
if(action == 'actionA'):
if(collection == 'collectionA'):
doActionA(collectionA)
elif(collection == 'collectionB'):
doActionA(collectionB)
if(action == 'actionB'):
if(collection == 'collectionA'):
doActionB(collectionA)
elif(collection == 'collectionB'):
doActionB(collectionB)
这段代码看起来设计得很糟糕,有没有更好的 pythonic 方法来实现它?
如果是这样,即没有其他可能的操作和收集,请结合您的陈述:
if(
action == 'actionA' and
collection == 'collectionA'
):
doActionA(collectionA)
elif(
collection == 'collectionB'
):
doActionA(collectionB)
if(
action == 'actionB' and
collection == 'collectionA'
):
doActionB(collectionA)
elif(
collection == 'collectionB'
):
doActionB(collectionB)
根据名称“选择”元素的经典方法是使用字典。字典可以包含任何类型的对象,包括函数。
collections = {'collectionA': collectionA; 'collectionB': collectionB}
doActions = {'actionA': doActionA; 'actionB': doActionB}
# do action, without error checking
doActions[action](collections[collection])
# do action, with default value
doActions.get(action, doDefaultAction)(collections.get(collection, defaultCollection))
# do action, only if values are correct
if action in doActions and collection in collections:
doActions[action](collections[collection])
我有以下条件语句:
if(action == 'actionA'):
if(collection == 'collectionA'):
doActionA(collectionA)
elif(collection == 'collectionB'):
doActionA(collectionB)
if(action == 'actionB'):
if(collection == 'collectionA'):
doActionB(collectionA)
elif(collection == 'collectionB'):
doActionB(collectionB)
这段代码看起来设计得很糟糕,有没有更好的 pythonic 方法来实现它?
如果是这样,即没有其他可能的操作和收集,请结合您的陈述:
if(
action == 'actionA' and
collection == 'collectionA'
):
doActionA(collectionA)
elif(
collection == 'collectionB'
):
doActionA(collectionB)
if(
action == 'actionB' and
collection == 'collectionA'
):
doActionB(collectionA)
elif(
collection == 'collectionB'
):
doActionB(collectionB)
根据名称“选择”元素的经典方法是使用字典。字典可以包含任何类型的对象,包括函数。
collections = {'collectionA': collectionA; 'collectionB': collectionB}
doActions = {'actionA': doActionA; 'actionB': doActionB}
# do action, without error checking
doActions[action](collections[collection])
# do action, with default value
doActions.get(action, doDefaultAction)(collections.get(collection, defaultCollection))
# do action, only if values are correct
if action in doActions and collection in collections:
doActions[action](collections[collection])