2017-02-17 107 views
-1

for循環中的語法是什麼意思?Python for循環的語法爲什麼

我特別迷茫什麼是

for X 

在下面的例子,爲什麼我使用「字母」是什麼意思?是否因爲'函數'是函數執行時我想返回的東西的單個組件?

我花了幾個小時在函數內切換單詞'letter','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 
+0

爲字母,打印信件中的每個字母。 '在「abcdef ...」中輸入字母:print(letter)' – Li357

+0

https://opentechschool.github.io/python-beginners/en/loops.html – Alexander

+0

您可以使用'line + = letter'作爲短手對於'line = line + letter'。另外我認爲值得一提的是,這個方法可以用'''.join(board [row_index])'來完成。它會加入board [row_index]的每個字母,在每個字母之間加上''''(無)。 – Alexander

回答

0

試着去思考「for x in letter」爲「用於在信每隔x」 例如,如果運行在Python下面的代碼:

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

You will get the output: 
A 
B 
C 
D 
None 

上面的代碼只是檢查在列表「small_list」 EVERY元件和印刷的相應的值。

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的for循環會解開元組的列表並支持分支以防止循環被破壞)

+0

第二個代碼中使用的語言 – kouty

+0

@kouty - 這就是C++。 – TigerhawkT3