我刚刚在Uni学习了半个学期的python。我真的很喜欢它,并希望得到一些关于如何编写更多“pythonic”代码的技巧。
这是我最近完成的一个任务中的__init__类。在我写这篇文章的时候,我正试图弄清楚如何使用lambdas重写它,或者用一种更简洁、更有效的方式来重写它,但我的时间已经用完了。
def __init__(self, dir):
def _read_files(_, dir, files):
for file in files:
if file == "classes.txt":
class_list = readtable(dir+"/"+file)
for item in class_list:
Enrol.class_info_dict[item[0]] = item[1:]
if item[1] in Enrol.classes_dict:
Enrol.classes_dict[item[1]].append(item[0])
else:
Enrol.classes_dict[item[1]] = [item[0]]
elif file == "subjects.txt":
subject_list = readtable(dir+"/"+file)
for item in subject_list:
Enrol.subjects_dict[item[0]] = item[1]
elif file == "venues.txt":
venue_list = readtable(dir+"/"+file)
for item in venue_list:
Enrol.venues_dict[item[0]] = item[1:]
elif file.endswith('.roll'):
roll_list = readlines(dir+"/"+file)
file = os.path.splitext(file)[0]
Enrol.class_roll_dict[file] = roll_list
for item in roll_list:
if item in Enrol.enrolled_dict:
Enrol.enrolled_dict[item].append(file)
else:
Enrol.enrolled_dict[item] = [file]
try:
os.path.walk(dir, _read_files, None)
except:
print "There was a problem reading the directory"如你所见,它有点笨重。如果任何人有时间或兴趣,我将非常感谢一些关于python最佳实践的技巧。
谢谢。
发布于 2010-05-31 12:00:57
有几件事可以稍微清理一下你的代码:
使用字典的setdefault。如果键丢失,则将其设置为您提供的默认值,然后返回它。否则,它将忽略第二个参数并返回字典中的内容。这就避免了笨拙的if语句。
Enrol.venues_dict.setdefault(key, []).append(file)
>>> x = {}
>>> x.setdefault(99, []).append(5)
>>> x.setdefault(99, []).append(6)
>>> x
{99: [5, 6]}
>>> x.setdefault(100, []).append(1)
>>> x
{99: [5, 6], 100: [1]}另一种可能是使用os.path.join来创建文件路径。这比仅仅进行字符串连接更安全。
os.path.join(dir, file)除此之外,在风格上看起来不错,IMO。
发布于 2010-05-31 15:18:20
除了orangeoctopus建议使用setdefault之外,您还可以将if-else重构为一个dispatcher (大型if-else和switch语句的典型替代品):
# list of 2-tuples: (bool func(string filename), handler_function)
handlers = [
((lambda fn: fn == "classes.txt"), HandleClasses),
((lambda fn: fn == "subjects.txt"), HandleSubjects),
((lambda fn: fn.endswith(".roll")), HandleRoll)
]那就这么做
for filename in files:
for matcher, handler in handlers:
if matcher(filename):
handler(filename)
break发布于 2010-05-31 15:05:08
如果你想长时间使用你的脚本(有些人会说很长),另一个要点是不要在新代码中使用不推荐使用的函数:
os.path.walk在Python3.x中消失了。现在,您可以改用os.walk。但是,os.walk与os.path.walk不同:它不接受签名中的处理函数。因此,重构您的代码将意味着比更改名称更多一点。
https://stackoverflow.com/questions/2941271
复制相似问题