Re: [問題] 良好的python編碼習慣
※ 引述《gbllggi (gbllggi)》之銘言:
: 借標題,想問問大家的習慣
: 剛學pyhton不久,想請問大家有什麼建議的習慣要養成呢?
: 例如可以簡化成一行的for loop該盡量寫成一行嗎?
說到這個單行 for loop,我到今年初才知道,有些情況下
單行反而比多行更好讀
舉例來說,如果要找某個 list item 是否符合某個條件︰
found = False
for item in list:
if exp(item):
found = True
break
if found:
# do thing
可以寫成︰
if any(exp(item) for item in list):
# do thing
而且 comprehension 有它自己的 scope,所以不必考慮變數被覆蓋的問題
dict, list, set 配合 comprehension,再加上 any, all, filter, map 函式
幾乎所有單層的 for 都能改成單行
我覺得 python 還可以考慮加上幾個函式
first(iterable, cb) # return first item that cb(item) is True
each(iterable, *cb) # invoke each cb for all items
reduce(cb, *iterable) # invoke cb with previous cb result for all items
: 或是一個function只處理一件事情?
: 還有以前已經寫好的code但有點醜、或亂,會為了維護方便還有容易分享
: 一直去更新它嗎?還是code能跑就好,等到要更新再說?
現在看覺得有點醜或亂,明年再看就完全不知道自己在幹麻了(真實經驗)
--
(* ̄▽ ̄)/‧★*"`'*-.,_,.-*'`"*-.,_☆,.-*`
http://i.imgur.com/oAd97.png

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.87.168
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1461353438.A.853.html
→
04/23 03:34, , 1F
04/23 03:34, 1F
→
04/23 03:35, , 2F
04/23 03:35, 2F
→
04/23 03:35, , 3F
04/23 03:35, 3F
推
04/23 04:38, , 4F
04/23 04:38, 4F
→
04/23 05:25, , 5F
04/23 05:25, 5F
→
04/23 05:27, , 6F
04/23 05:27, 6F
→
04/23 05:27, , 7F
04/23 05:27, 7F
→
04/23 07:54, , 8F
04/23 07:54, 8F
→
04/23 08:05, , 9F
04/23 08:05, 9F
→
04/23 08:07, , 10F
04/23 08:07, 10F
→
04/23 09:10, , 11F
04/23 09:10, 11F
→
04/23 09:10, , 12F
04/23 09:10, 12F
→
04/23 09:25, , 13F
04/23 09:25, 13F
→
04/23 09:32, , 14F
04/23 09:32, 14F
→
04/23 09:32, , 15F
04/23 09:32, 15F
→
04/23 09:33, , 16F
04/23 09:33, 16F
→
04/23 09:51, , 17F
04/23 09:51, 17F
→
04/23 11:57, , 18F
04/23 11:57, 18F
→
04/23 11:59, , 19F
04/23 11:59, 19F
→
04/23 13:55, , 20F
04/23 13:55, 20F
→
04/23 13:56, , 21F
04/23 13:56, 21F
推
08/10 01:22, , 22F
08/10 01:22, 22F
→
08/10 01:22, , 23F
08/10 01:22, 23F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 4 篇):