Naming variables inside nested lists in Python?

As in the title, is there a way to name the variables (i.e. lists) used in understanding a nested list in Python?

I could come up with an example, but I think the question is clear enough.

Here is an example of pseudocode:

[... [r for r in some_list if r.some_attribute == something_from_within_this_list comprehension] ... [r for r in some_list if r.some_attribute == something_from_within_this_list comprehension] ...]

Is there a way to avoid repetition here and just add a variable for this temporary list just for use in list comprehension?

CLARIFICATION: Understanding the list is already working fine, so this is not a question of โ€œcan this be done with the listโ€. And this is faster than the original form of the for expression, so this is not one of the questions โ€œfor statements and lists.โ€ It's just about making list comprehension easier by making variable names for internal variables just for list comprehension. Just googling around, I really did not find the answer. I found this and this , but thatโ€™s not quite what I want.

+3
source share
4 answers

Based on my understanding of what you want to do, no, you cannot do this.

,

[expression(x, y) for x in expression_that_creates_a_container 
                  for y in some_other_expression_that_creates_a_container(x)
                  if predicate(y, x)]

, , . : , . , , for my_variable in.

, , . , itertools, .

+3

, , , " " . , .

:

, 1000. python :

def pythagoreanTriplet(sum):
    for a in xrange(1, sum/2):
        for b in xrange(1, sum/3):
            c = sum - a - b
            if c > 0 and c**2 == a**2 + b**2:
               return a, b, c

:

def pythagoreanTriplet2(sum):
    return next((a, b, sum-a-b) for a in xrange(1, sum/2) for b in xrange(1, sum/3) if (sum-a-b) > 0 and (sum-a-b)**2 == a**2 + b**2)

, 3 (sum-a-b), , . , , - , :

def pythagoreanTriplet3(sum):
    return next((a, b, c) for a in xrange(1, sum/2) for b in xrange(1, sum/3) for c in [sum-a-b] if c > 0 and c**2 == a**2 + b**2)

... , , . 3 cProfile, , , :

  • : 0.077
  • Secnd: 0.087
  • : 0.109
+2

"", .

f = lambda i,j: int(i==j) #A dummy function (here Kronecker delta)    
a = tuple(tuple(i + (2+f_ij)*j + (i + (1+f_ij)*j)**2
                for j in range(4)
                for f_ij in (f(i,j),) ) #"Assign" value f(i,j) to f_ij.
          for i in range(4) )
print(a)
#Output: ((0, 3, 8, 15), (2, 13, 14, 23), (6, 13, 44, 33), (12, 21, 32, 93))

, f. , "", .

+1
source

I'm just going to go on a limb because I have no idea what you're really trying to do. I'm just going to guess that you are trying to train more than you should be in one expression. Do not do this, just assign subexpressions to the variables:

sublist = [r for r in some_list if r.some_attribute == something_from_within_this_list comprehension]
composedlist = [... sublist ... sublist ...]
0
source

Source: https://habr.com/ru/post/1779924/


All Articles