为什么这种语法适用于Python for循环

时间:2017-02-17 05:07:10

标签: python python-3.x for-loop syntax

for循环中的语法用简单的英语表示什么?

我特别对

的含义感到困惑
for X

在下面的示例中,为什么我会使用'来表示字母'?是因为'字母'是函数执行后我想要返回的东西的个别组件吗?

花了我几个小时的时间来切换字母',' line',' row'和' row_index'在功能中获得有用的东西。

我必须编写的每个函数作为赋值,我都有同样的困惑。

def make_str_from_row(board, row_index):
""" (list of list of str, int) -> str

Return the characters from the row of the board with index row_index
as a single string.

>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
"""

line = ''

for letter in board[row_index]:
        line = line + letter

return line

2 个答案:

答案 0 :(得分:1)

语法与用于存在测试的语法相同;

letter   = 'a'
mystring = 'Hello World'
if letter in mystring:
    print("Letter "+letter+" in "+mystring)
else:
    print("Letter "+letter+" not in "+mystring)

在这个例子中,你问翻译一个问题;如果letter中的mystring(是),则打印"字母在我的字符串中,"否则打印"字母不在我的字符串中。"

for循环询问相同的问题,除了列表/字符串/容器中的每个字母; for {every} letter in board[row_index]连接行和字母。

我学到这一点的方式来自我过去使用boost.foreach循环的经验。如果你曾经使用过它们,你就会明白循环会自动遍历容器中的每个项目,给定容器和容器中的项目的缓冲区;

std::string hello = "Hello world!";

BOOST_FOREACH(char ch, hello)
{
    std::cout << ch; // Print each character individually
}

正如您所看到的,boost.foreach循环和Python for循环在功能上是等效的。 (顺便说一句,你会发现Python for循环更灵活。用于循环的Python将解包元组列表并支持分支,以防循环没有被破坏)

答案 1 :(得分:0)

试着想一下&#34;对于字母中的x&#34; as&#34;对于字母中的每个x&#34; 例如,如果您在Python中运行以下代码:

small_list = ["A","B","C","D"]
for x in small_list:
    print x

You will get the output:
A
B
C
D
None

上面的代码只检查了列表中的每个元素&#39; small_list&#39;并打印相应的值。