单行for循环作为函数参数 [英] One-line for loop as a function argument

查看:107
本文介绍了单行for循环作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

该代码如何(以及为什么)起作用?发生什么事了?通常我不能使用这种语法.另外,如果它不在某些 function 中作为参数,则该语法也不存在.

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)

推荐答案

在函数调用中使用时,语法:

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 ().

这篇关于单行for循环作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆