我正在掌握python中的列表,但是當談到使用這兩個函數時的差異。列表中的項目和我在範圍(0,len(x))中的蟒蛇之間的區別
def print_list(x):
for j in range (0, len(x)):
print x[j]
和
def print_list(x):
for item in list:
j = 0
print x[j]
j++
誰能解釋給初學者?謝謝!
我正在掌握python中的列表,但是當談到使用這兩個函數時的差異。列表中的項目和我在範圍(0,len(x))中的蟒蛇之間的區別
def print_list(x):
for j in range (0, len(x)):
print x[j]
和
def print_list(x):
for item in list:
j = 0
print x[j]
j++
誰能解釋給初學者?謝謝!
我認爲
def print_list(x):
for j in range (0, len(x)):
print x[j]
是如何循環在運行C++。所以你直觀地理解了這一點。這裏,range
生成(查找generators)值0
到len(x)
和for
語句遍歷它們。
正如註釋中指出的,你的第二種語法是錯誤的。我假設你的意思
def print_list(x):
for item in x:
print(item)
的for
聲明遍歷列表中的每x
item
。
因此,如果您的列表是[1,3,5,7,9]
,在第一個循環中,item
將具有值1
。在第二個循環中,item
將具有值3
。在第三個循環中,item
將具有值5
。等等。
當所有值迭代完畢後,for
循環結束。
第一個例子是正確的,它應該足夠pythonic。第二個是不正確的。
def print_list(x):
for item in list: #where is the iterable oject called list? This shuold be x
j = 0 # if you use a counter like j you shuold be defining before the loop otherwise you keep resetting it to 0.
print x[j]
j++
如果您想在列表中打印列表中的所有元素並將它們打印在其上,那麼這種方法會更加Python化和更好。
def print_list(list_item):
for element in list_item:
print(element)
你並不需要使用範圍和Len像在第一個例子中,列表是迭代的對象,所以你可以做像上面的例子,而不recuring爲range()。
第二個問題還有一個錯誤:'j ++'語法無效。它應該是'j + = 1'。 – zondo
第二個似乎不是有效的Python語法; 'j ++'必須是'j + = 1',並且'j = 0'初始化必須在循環之外。 – ZdaR
另外,第二個中沒有'list'變量,所以'for'循環會崩潰(除非在其他地方創建了一個變量'list')。在你問這個問題之前,你應該確保你的代碼至少有**運行**。 –