[問題] 一行表列 ['cat','dog','rabbit'] 的字元

看板Python作者 (四元)時間10年前 (2015/01/20 22:18), 10年前編輯推噓3(307)
留言10則, 4人參與, 最新討論串1/1
最近在看 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

01/20 22:42, , 1F
"".join(['cat','dog','rabbit'])
01/20 22:42, 1F

01/20 22:43, , 2F
''.join(['cat', 'dog', 'rabbit'])
01/20 22:43, 2F

01/21 00:01, , 3F
list({c for w in ['cat','dog','rabbit']for c in w)
01/21 00:01, 3F
原本的標題寫得不太好 :-( 結果要像是 ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] ※ 編輯: fourdollars (220.135.121.238), 01/21/2015 10:55:23

01/21 11:31, , 4F
l = ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', ...
01/21 11:31, 4F

01/21 11:31, , 5F
[c for i, c in enumerate(l) if c not in l[:i]]
01/21 11:31, 5F

01/21 11:34, , 6F
或 [c for c in set(l)],不過 set 不保證順序,若要
01/21 11:34, 6F

01/21 11:36, , 7F
順序一致可以參考 OrderedSet http://bit.ly/1C7ns1O
01/21 11:36, 7F

01/21 12:18, , 8F
t = []; [c for w in l for c in w if c not in t \
01/21 12:18, 8F

01/21 12:18, , 9F
and t.extend(c)]
01/21 12:18, 9F

01/21 12:21, , 10F
上面這行是當 l = ['cat', 'dog', 'rabbit'] 時。
01/21 12:21, 10F
文章代碼(AID): #1KlcEdac (Python)
文章代碼(AID): #1KlcEdac (Python)