简体   繁体   中英

Why does this generator expression raise a syntax error?

This line throws an error saying I didn't define x even though I stated that x is an element of the list:

any(i.isdigit() for i in x for x in [name.id for name in all.names])

So x is a string element of the list, and I am checking if for some character in each element x , that element x contains a number using .isdigit() . How come this doesn't work?

Comprehensions/generator expressions in Python nest from left to right (yeah, it can be a bit confusing). Swap them:

for x in [name.id for name in all.names] for i in x

Or separate out for clarity:

def contains_digit(s):
    return any(c.isdigit() for c in s)


any(contains_digit(name.id) for name in all.names)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM