简体   繁体   English

有关“ for”循环的一般问题

[英]General questions about “for” loops

I'm beginning to learn Python by following an introductory text and have come across an exercise that implements a for loop to read files from a directory. 我通过遵循介绍性文字开始学习Python,并且遇到了一个实现for循环以从目录读取文件的练习。 I've used for loops before in R and Java and I have some questions. 我以前在R和Java中使用for循环,但我有一些问题。 I'm hoping the community could help me wrap my head around about for loops in general. 我希望社会各界能帮助我绕到我的头有关for一般循环。

  1. It seems (in Python at least) that special characters and numbers can't be used as the "name" in loop. 似乎(至少在Python中)特殊字符和数字不能用作循环中的“名称”。 What's the reason for this? 这是什么原因?

    ex: 例如:

     for @ in data: print (@, end= ' ') 

    will produce an error. 会产生一个错误。 However replacing @ with x or name for example is fine. 但是,例如用xname替换@可以。 Is this one of those things we accept, don't question, and move on? 这是我们接受,不质疑并继续前进的事情之一吗?

  2. How does the for loop know (or evaluate) whether an object is "iterable"? for循环如何知道(或评估)对象是否“可迭代”?

  1. As others have mentioned, see the rules for Python variable, ie identifier, names: https://docs.python.org/3/reference/lexical_analysis.html#identifiers 正如其他人提到的,请参阅Python变量的规则,即标识符,名称: https : //docs.python.org/3/reference/lexical_analysis.html#identifiers

  2. An object is iterable if it has the __next__() method defined . 如果已定义 __next __()方法,则该对象是可迭代的。 See also https://wiki.python.org/moin/ForLoop 另请参见https://wiki.python.org/moin/ForLoop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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