作者fourdollars (四元)
看板Python
標題[問題] 一行表列 ['cat','dog','rabbit'] 的字元
時間Tue Jan 20 22:18:08 2015
最近在看
http://interactivepython.org/runestone/static/pythonds/index.html
看到 Control Structures 最底下有個自我測驗
原本是做到像是下一行就可以了
> print([ch for word in ['cat','dog','rabbit'] for ch in word])
但是看到 "For an extra challence, see if you can figure out how to remove the
duplicates." 然後又看了底下的影片覺得用 list 包住 set 再包原本的 list 有點鳥
請問有沒有人有其它不同的一行解法嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.15.0.129
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1421763495.A.926.html
1F:→ ocean5566: "".join(['cat','dog','rabbit']) 01/20 22:42
2F:→ qoorocker: ''.join(['cat', 'dog', 'rabbit']) 01/20 22:43
3F:→ alibuda174: list({c for w in ['cat','dog','rabbit']for c in w) 01/21 00:01
原本的標題寫得不太好 :-(
結果要像是 ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
※ 編輯: fourdollars (220.135.121.238), 01/21/2015 10:55:23
4F:推 changyuheng: l = ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', ... 01/21 11:31
5F:→ changyuheng: [c for i, c in enumerate(l) if c not in l[:i]] 01/21 11:31
6F:→ changyuheng: 或 [c for c in set(l)],不過 set 不保證順序,若要 01/21 11:34
8F:推 changyuheng: t = []; [c for w in l for c in w if c not in t \ 01/21 12:18
9F:→ changyuheng: and t.extend(c)] 01/21 12:18
10F:推 changyuheng: 上面這行是當 l = ['cat', 'dog', 'rabbit'] 時。 01/21 12:21