作者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/cn.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