gpt4 book ai didi

python - 根据输入标志返回不同变量的优雅方式

转载 作者:行者123 更新时间:2023-12-01 15:34:25 24 4
gpt4 key购买 nike

我有一个函数可以打开一个文本文件,解析一堆数据并返回一个数组中的数字结果。现在,我还希望此函数能够即时执行一些可选计算,并在需要时返回这些值。

对于单个标志,这是相当干净的,例如:

def read_data(file_name, calc_a=False):
# do normal parsing and store data in 'xyz'
if calc_a:
# calc some other stuff and store in 'a'
return xyz, a
else:
return xyz

现在如果我想要多个可选标志,事情很快就会变得困惑,例如:

def read_data(file_name, calc_a=False, calc_b=False):
# do normal parsing and store data in 'xyz'
if calc_a:
# calc some other stuff and store in 'a'
if calc_b:
# calc some other stuff and store in 'b'

if calc_a and calc_b:
return xyz, a, b
elif calc_a:
return xyz, a
elif calc_b:
return xyz, b
else:
return xyz

有没有更简洁的方法来处理这种情况?

最佳答案

def read_data(file_name, *extras):
# Read the data from file_name, organizing in a dict,
# using the key names that your caller will pass into the function.
# In this example, we have the main data that will always be
# returned, plus optional data stored under keys a, b, c, d.
data = dict(_main = 'MAIN', a = 'AA', b = 'BB', c = 'CC', d = 'DD')

# Return a tuple, list, or even dict of that data.
ks = sorted(data.keys())
return tuple(data[k] for k in ks if k in extras or k == '_main')

# Caller requests the optional data they want.
# This example shows the caller passing a list of optional data keys.
# You could also have them pass keyword args instead.
wanted = 'a b d'.split()
print read_data('data_file', *wanted) # ('MAIN', 'AA', 'BB', 'DD')

关于python - 根据输入标志返回不同变量的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19352835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com