[英]Coding the Python way
我剛剛在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最佳實踐的一些提示。
謝謝。
結合可以清理代碼的東西:
使用字典的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的風格看起來不錯。
除了orangeoctopus使用setdefault
的建議之外,您還可以將if-else重構為調度程序(大型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
另一個重要的一點是,如果你想長時間使用腳本(有些人會說非常長),就是不要在新代碼中使用不推薦使用的函數:
os.path.walk
在python 3.x中消失了。 現在你可以使用os.walk
。 但是os.walk
與os.path.walk
不同:它不接受簽名中的處理函數。 因此,重構代碼意味着更改名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.