gpt4 book ai didi

python - 对如何在 python 中将代码编写为函数感到困惑

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:58 25 4
gpt4 key购买 nike

大家好,我还在学习 python 3,我更熟悉 VBA。我有下面的 python 代码,它的作用是对 csv 文件进行排序并将转换保存在新文件中。目前我可以在空闲状态下运行它并且它可以工作。我需要能够将其定义为函数,以便我可以从 VBA 按钮调用它。

from xlwings import Workbook, Range
# file group_by_trailing_py2.py
import os
import csv
from itertools import groupby

DELIM=';'
IN_FILENAME = 'My Product.csv'
OUT_FILENAME = 'My Product.grouped.csv'


keyfunc = lambda row: row[1:]

with open(IN_FILENAME) as csv_file:
``rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc)

it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0],
groupby(rows, key=keyfunc))

with open(OUT_FILENAME, 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=DELIM)
for row in it:
writer.writerow(row)

最佳答案

def f():
DELIM=';'
IN_FILENAME = 'My Product.csv'
OUT_FILENAME = 'My Product.grouped.csv'


keyfunc = lambda row: row[1:]
with open(IN_FILENAME) as csv_file:
``rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc)

it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0],
groupby(rows, key=keyfunc))

with open(OUT_FILENAME, 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=DELIM)
for row in it:
writer.writerow(row)

f()

关于python - 对如何在 python 中将代码编写为函数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33664747/

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