[問題] dict問題

看板Python作者 (天羽)時間7年前 (2018/03/18 19:40), 7年前編輯推噓10(10022)
留言32則, 5人參與, 7年前最新討論串1/1
現在我有一組程式碼 from collections import defaultdict import numpy as np s=[11,55,22,22,55,22,55,22,33,33,55,33,44,44,55,55,44,44] d = defaultdict(list) for k,l in [(v,t) for t,v in enumerate(s)]: d[k].append(l) print(d.items()) 其目的是找出重複的項 並且顯示在矩陣中的位置 而執行結果會是這樣 dict_items([(11, [0]), (55, [1, 4, 6, 10, 14, 15]), (22, [2, 3, 5, 7]), (33, [8, 9, 11]), (44, [12, 13, 16, 17])]) 現在希望說可以把結果抽取出來 像是這樣 a(0)=11,b(0)=[0] a(1)=55,b(1)=[1, 4, 6, 10, 14, 15] . . . . 想請問應該要對程式碼做些什麼修改 才可以達到所希望的目的? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 120.105.133.228 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1521373230.A.363.html

03/18 22:21, 7年前 , 1F
也就是說 a(i) = s[i], b(i) = d[s[i]] ?
03/18 22:21, 1F
對唷 之前我有試了一下 這麼做只會顯示最後一個的值 有想過用append 不過不確定要怎麼寫QQ

03/18 22:37, 7年前 , 2F
咦,我照著你的 code 打,跑出來是對的耶
03/18 22:37, 2F
0.0 我明天再試試看! 說不定是我自己打錯之類的XDD 先謝過P大! ※ 編輯: st40182 (114.41.179.173), 03/18/2018 22:54:11

03/19 01:02, 7年前 , 3F
S_element = set(s)
03/19 01:02, 3F

03/19 01:02, 7年前 , 4F
b = {}
03/19 01:02, 4F

03/19 01:02, 7年前 , 5F
for i in S_element:
03/19 01:02, 5F

03/19 01:02, 7年前 , 6F
b[i] = []
03/19 01:02, 6F

03/19 01:02, 7年前 , 7F
for idx, item in enumerate(s):
03/19 01:02, 7F

03/19 01:02, 7年前 , 8F
b[i].append(idx)
03/19 01:02, 8F

03/19 01:02, 7年前 , 9F
# a = s (?
03/19 01:02, 9F

03/19 01:02, 7年前 , 10F
不知道這樣能不能達到你的目的,差別在位置的list是
03/19 01:02, 10F

03/19 01:02, 7年前 , 11F
用value本身當key(ps手機打的,可能會有些問題)
03/19 01:02, 11F

03/19 01:03, 7年前 , 12F
啊....indent被吃掉了 不過應該還能閱讀
03/19 01:03, 12F

03/19 02:44, 7年前 , 13F
樓上j大 你這樣本身跟他用一組dict做出來的事一樣
03/19 02:44, 13F

03/19 02:45, 7年前 , 14F
順便提醒原po 你enumerate那不需要那樣子寫
03/19 02:45, 14F

03/19 02:46, 7年前 , 15F
for i, v in enumerate(s) 就可以拿到index跟val了
03/19 02:46, 15F

03/19 02:47, 7年前 , 16F
不需要一個在list裡建tuple再把tuple取出來 太多餘
03/19 02:47, 16F

03/19 02:49, 7年前 , 17F
a = list(d) b = [] for v in a: b.append(d[v])
03/19 02:49, 17F

03/19 05:36, 7年前 , 18F
幫樓上 h 大補充,b 可以用 list comprehensions 就好
03/19 05:36, 18F

03/19 05:36, 7年前 , 19F
b = [d[v] for v in a]
03/19 05:36, 19F

03/19 05:37, 7年前 , 20F
或是另一種方法:
03/19 05:37, 20F

03/19 05:37, 7年前 , 21F
a = list(d) # 等同於 list(d.keys())
03/19 05:37, 21F

03/19 05:37, 7年前 , 22F
b = list(d.values())
03/19 05:37, 22F

03/19 09:17, 7年前 , 23F
抱歉請問for k,l in [(v,t) for t,v in e(s)]: 這段
03/19 09:17, 23F

03/19 09:18, 7年前 , 24F
意思是什麼呢
03/19 09:18, 24F

03/19 11:31, 7年前 , 25F
第二種方法我是想說dict是unorder不知道直接取list會
03/19 11:31, 25F

03/19 11:31, 7年前 , 26F
不會沒對應到,不過第一種方法確實是不錯的 可以把b
03/19 11:31, 26F

03/19 11:31, 7年前 , 27F
縮成一行解決
03/19 11:31, 27F

03/19 11:33, 7年前 , 28F
t大,我上面有補充他那段是可以簡化的
03/19 11:33, 28F

03/19 14:34, 7年前 , 29F
如果沒有中途修改 dict 的話,dict.keys() 跟
03/19 14:34, 29F

03/19 14:36, 7年前 , 30F
dict.values() 順序會是對應的喔,官方文件有提到。
03/19 14:36, 30F

03/19 16:48, 7年前 , 31F
看不太懂他(v,t)跟t,v
03/19 16:48, 31F

03/19 18:57, 7年前 , 32F
上了一課了
03/19 18:57, 32F
文章代碼(AID): #1Qhb0kDZ (Python)
文章代碼(AID): #1Qhb0kDZ (Python)