首页 > 解决方案 > 如何用python编码方式编写我的代码?

问题描述

我用 python 写了一个原始代码,我怎样才能让它看起来更像一个 python 结构,

我还没有为每个函数创建类和对象,我想返回而不是打印

我怎样才能明智地分离功能并在最后返回?

with open(r'features.csv', 'r') as f:
checker = lambda i: bool(i and i.strip())
reader = csv.reader(f)
header = next(reader)
folders = next(
    {
        header[0]: [row[0]],
        'Feature Name': list(filter(checker, row[:1])),
        'Child folder': list(filter(checker, row[1:]))
    } for row in reader
)
foldersinlist = list(folders.values())
lists = sum(foldersinlist, [])
print(lists)

有什么想法吗?

标签: python

解决方案


如果我们知道您要如何处理返回的数据会很有帮助,我们可以为您提供更多帮助,但这应该会让您朝着正确的方向前进。

def my_function():
    with open(r'features.csv', 'r') as f:
    checker = lambda i: bool(i and i.strip())
    reader = csv.reader(f)
    header = next(reader)
    folders = next(
        {
            header[0]: [row[0]],
            'Feature Name': list(filter(checker, row[:1])),
            'Child folder': list(filter(checker, row[1:]))
        } for row in reader
    )
    foldersinlist = list(folders.values())
    lists = sum(foldersinlist, [])
    # print(lists) #Instead of this, let's return the value:

    return lists

my_data = my_function() #we're setting my_data to the returned-value of my_function

print (my_data) #Now you can us my_data wherever you need the result of my_function

推荐阅读