gpt4 book ai didi

python - 从函数返回列表和整数的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 21:52:30 24 4
gpt4 key购买 nike

我有一个读取 csv 的函数给我一个列表。然后,我找到该列表的最大值,然后从函数返回该列表和最大值。我想知道执行此操作的最佳方法,以使我的代码更高效且更具可读性。我对 python 还比较陌生,我正在尝试使用最佳实践来构建我的技能。目前,我有:

def getLayerList(layersLoc):
import csv
layerList = []
reader = csv.reader(open(layerLoc))
for list in reader:
for layer in list:
layerList.append(int(layer))
numLayers = max(layerList)
return layerList, numLayers

我可以将图层列表和 numLayers 称为该函数的 [0],[1] 实例。我担心的是,如果我返回越来越多不同类型的数据,将很难跟踪它们并且很难读取它们。我应该使用类吗?更Pythonic 的方法是什么?

最佳答案

从性能角度来看,我首先要避免的是在函数本身中调用import。在顶层进行导入将避免重复检查 sys.modules 来查看模块是否已导入。

接下来,在迭代后调用 max 会再次有效地迭代该列表。我会跟踪循环内的最大值,以避免对列表进行第二次迭代。

最后,我将使用 with 语句打开文件,这样您就知道该文件在阅读器的生​​命周期内保持打开状态,这实际上可以在函数外部处理

# imports go up here unless you have a very specific reason not to
import csv

# naming should be snake_case
def get_layer_list(my_reader):
layer_list = []
num_layers = 0

# don't shadow builtin names like list
for lst in my_reader:
for layer in lst:
val = int(layer)

# do that check here
if val > num_layers:
num_layers = val

layer_list.append(val)

# now, num_layers has already been checked
return layer_list, num_layers


with open('somefile.csv') as fh:
reader = csv.reader(fh)

# this is how you'd call the function
layers, nlayers = get_layer_list(reader)

# do something with layers and nlayers

否则,返回中的多个值是完全Pythonic的。当元组解包通常就足够时,unPythonic 就是对返回值进行索引。

# instead of this
x = return_two_values()
a = x[0]
b = x[1]

# do this
a, b = return_two_values()

关于python - 从函数返回列表和整数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59885258/

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