2013-05-04 84 views
1

我創建列表中的某些隨機數的工作方案,計算他們的occurrencies,並把結果在字典中,看起來如下:如何訪問嵌套comprehensioned列表

random_ints = [random.randint(0,4) for _ in range(6)] 
dic = {x:random_ints.count(x) for x in set(random_ints)]) 

使因爲,[0,2,1,2,1,4]我得到了{0:1,1:2,2:2,4:1}

我想知道它是否有可能在一個班輪,最好不使用庫函數 - 我想看看python有什麼可能:) 當我嘗試將兩行整合到一行中時,我不知道如何表達兩個引用到同一個理解的列表random_ints .. ???我希望是這樣的:

dic = {x:random_ints.count(x) for x in set([random.randint(0,4) for _ in range(6)] as random_ints)) 

這當然不工作...

我看了(巢)列表在這裏推導了對SO,但我卻並不適用,我發現我的問題解決方案。

謝謝,s。

回答

2

有幾種方法可以達到這樣的效果,但沒有一種方法正是您想要的。你不能做的是將名字簡單地綁定到list/dict理解中的固定值。如果random_ints不依賴於dic所需的任何迭代變量,最好按照您的操作方式進行操作,並分別創建random_ints

從概念上講,應該在詞典理解中唯一需要爲詞典中的每個項目分別創建的東西。 random_ints不符合此標準;你總體上只需要一個random_ints,所以沒有理由把它寫在字典理解中。

這就是說,一個辦法做到這一點是僞造它通過遍歷包含您random_ints一個元素的列表:

{x:random_ints.count(x) for random_ints in [[random.randint(0,4) for _ in range(6)]] for x in set(random_ints)} 
+0

因此,這個假的迭代單元素列表(或像@Schoolboy的解決方案中的1元組)是獲得理解名單的方式,以便在主理解中進一步引用 - 酷。但是不應該這麼做,因爲它的概念上並不乾淨 - 即使我不再需要隨機列表。我想我知道了:) - 非常感謝! – user1243904 2013-05-04 19:38:30

+0

@ user1243904:一般來說,嘗試將東西壓縮成一條線只是簡潔而不是Pythonic。如果兩條線更具可讀性,則只需使用兩條線。 – BrenBarn 2013-05-04 19:42:20

1

列表中使用 as dict-comprehension將不起作用。

試試這個:

dic = {x:random_ints.count(x) 
     for random_ints in ([random.randint(0,4) for _ in range(6)],) 
     for x in set(random_ints)) 

我認爲使用collections.Counter是一個更好的主意:

>>> import collections, random 
>>> c = collections.Counter(random.randint(0, 6) for _ in range(6)) 
>>> c 
Counter({6: 3, 0: 1, 3: 1, 4: 1}) 
+0

感謝,完美的作品。 – user1243904 2013-05-04 19:55:34

2

這裏是一個班輪依靠randomcollections模塊。

>>> import collections 
>>> import random 
>>> c = collections.Counter(random.randint(0, 6) for _ in range(100)) 
>>> c 
Counter({2: 17, 1: 16, 0: 14, 3: 14, 4: 14, 5: 13, 6: 12}) 
+0

儘管這使用了一個庫模塊,但它在性能上比使用'.count()'更好,因爲它不會顯示二次行爲。 – DSM 2013-05-04 18:58:50