Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
Uso de bucles 'while' en una lista de comprensión

Digamos que tengo una función:

 x=[] i=5 while i<=20: x.append(i) i=i+10 return x

¿Hay alguna manera de convertirlo en una lista de comprensión como esta?

 newList = [i=05 while i<=20 i=i+10]

Me sale un error de sintaxis.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

No necesitas una lista de comprensión para eso. range simplemente hará:

 list(range(5, 21, 10)) # [5, 15]

Un bucle while no es posible dentro de una lista de comprensión. En su lugar, podrías hacer algo como esto:

 def your_while_generator(): i = 5 while i <= 20: yield i i += 10 [i for i in your_while_generator()]
over 4 years ago · Santiago Trujillo Report

0

No, no puede usar while está en una lista de comprensión.

Según la especificación gramatical de Python , solo se permiten las siguientes expresiones atómicas:

 atom: ('(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictorsetmaker] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')

La expresión correspondiente a la comprensión de una lista - testlist_comp se parece a la siguiente en Python 3:

 testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

Aquí, las únicas declaraciones permitidas son

 test: or_test ['if' or_test 'else' test] | lambdef star_expr: '*' expr comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]

donde

 comp_if: 'if' test_nocond [comp_iter] comp_iter: comp_for | comp_if

No hay una sola instrucción while permitida en ninguna parte. Las únicas palabras clave que puede usar son for , for y for loop.

Solución

Use un bucle for o aproveche itertools .

over 4 years ago · Santiago Trujillo Report

0

No hay ninguna sintaxis para esto, pero puede usar itertools. Por ejemplo:

 In [11]: from itertools import accumulate, repeat, takewhile In [12]: list(takewhile(lambda x: x <= 20, accumulate(repeat(1), lambda x, _: x + 10))) Out[12]: [1, 11]

(Sin embargo, eso no es Pythonic. Se debe preferir la solución del generador o la solución explícita).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!