python - 如何用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)
有什么想法吗?
解决方案
如果我们知道您要如何处理返回的数据会很有帮助,我们可以为您提供更多帮助,但这应该会让您朝着正确的方向前进。
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
推荐阅读
- html - 使 @Html.RadioButtonFor 为必需
- excel - 需要将基于行的转换/转置为基于列的
- python - 如何在 Python 中将多个文本文件合并为一个 csv 文件
- vue.js - 如何访问通过道具传递给组件的对象方法
- sql-server-2005 - 如何在存储过程中创建查询 sqlserver 以随机显示数据
- mysql - SQL - 查询两个项目之间的链接信息
- node.js - 没有互联网访问的节点链码实例化
- javascript - 为什么我的导航栏没有在 Wordpress 中扩展?
- angular - 更新到 16.0.3 后泳道/ngx-datatable 不起作用(列似乎是问题所在)
- php - 使用 csrf_token 卷曲登录