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

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -