python - how to access a nested comprehensioned-list -


i have working solution creating list of random numbers, count occurrencies, , put result in dictionary looks following:

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

so for, [0,2,1,2,1,4] {0: 1, 1: 2, 2: 2, 4:1}

i wondering if possible express in 1 liner, preferably without use of library function - want see what's possible python :) when try integrate 2 lines in 1 dont know howto express 2 references same comprehensioned list of random_ints ..??? expected like:

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

which of course not work...

i looked (nested) list comprehensions here on so, not apply solutions found problem.

thanks, s.

there couple ways achieve that, none of them want. can't simple binding of name fixed value inside list/dict comprehension. if random_ints not depend on of iteration variables needed dic, it's better way did it, , create random_ints separately.

conceptually, things should in dict comprehension things need created separately each item in dict. random_ints doesn't meet criterion; need 1 random_ints overall, there's no reason put in dict comprehension.

that said, 1 way fake iterating on one-element list containing random_ints:

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

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -