One-line for loop as a function argument

本小妞迷上赌 提交于 2020-02-27 08:54:06

问题


def strange_syntax(stuff):
    return ".".join(item for item in stuff)

How (and why) works this code? What happens here? Normally I can't use this syntax. Also, this syntax doesn't exist if it's not inside some function as an argument.

I know, I could do the same with:

def normal_syntax(stuff):
    return ".".join(stuff)

回答1:


When used in a function call, the syntax:

f(a for a in b)

implicitly is compiled as a generator, meaning

f((a for a in b))

This is just syntactic sugar, to make the program look nicer. It doesn't make much sense to write directly in the console

>>>a for a in b

because it's unclear if you want to create a generator, or perform a regular loop. In this case you must use the outer ().




回答2:


This is called a generator expression.

It works just like a list comprehension (but evaluating the iterated objects lazily and not building a new list from them), but you use parentheses instead of brackets to create them. And you can drop the parentheses in a function call that only has one argument.

In your specific case, there is no need for a generator expression (as you noted) - (item for item in stuff) gives the same result as stuff. Those expressions start making sense when doing something with the items like (item.strip() for item in stuff) (map) or (item for item in stuff if item.isdigit()) (filter) etc.



来源:https://stackoverflow.com/questions/48205442/one-line-for-loop-as-a-function-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!