看板 Python 關於我們 聯絡資訊
最近在看 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://www.ptt.cc/bbs/Python/M.1421763495.A.926.html
ocean5566: "".join(['cat','dog','rabbit']) 01/20 22:42
qoorocker: ''.join(['cat', 'dog', 'rabbit']) 01/20 22:43
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
changyuheng: l = ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', ... 01/21 11:31
changyuheng: [c for i, c in enumerate(l) if c not in l[:i]] 01/21 11:31
changyuheng: 或 [c for c in set(l)],不過 set 不保證順序,若要 01/21 11:34
changyuheng: 順序一致可以參考 OrderedSet http://bit.ly/1C7ns1O 01/21 11:36
changyuheng: t = []; [c for w in l for c in w if c not in t \ 01/21 12:18
changyuheng: and t.extend(c)] 01/21 12:18
changyuheng: 上面這行是當 l = ['cat', 'dog', 'rabbit'] 時。 01/21 12:21