jst*_*u21 2 python for-loop python-3.x
谁能详细解释一下这是什么意思?f for f in...例如
list = [f for f in os.listdir(os.getcwd()) if os.path.isdir(f)]
print(list)
Run Code Online (Sandbox Code Playgroud)
我了解基本 for 循环的语法,但我已经多次看到这种类型的事情,并且发现它非常令人困惑。我一直在搜索,我所能找到的只是有关格式化的信息。我大约一个月前才开始学习Python,并且仍在学习中。感谢您的任何帮助!
小智 6
假设您要创建一个值为 0 到 100 的列表
list = [i for i in range(100)]
Run Code Online (Sandbox Code Playgroud)
当从 0 迭代到 100 时,这里i将被添加到列表中。
如果您想要任何规则,可以if在循环中使用语句,例如:
list = [i for i in range(100) if i%2 == 0]
Run Code Online (Sandbox Code Playgroud)
由于该if语句,这里只有能被 2 整除的数字才会被添加到列表中。