溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python中for循環(huán)變量作用域及用法詳解

發(fā)布時間:2020-08-31 06:53:01 來源:腳本之家 閱讀:479 作者:icemans2010 欄目:開發(fā)技術

在講這個話題前,首先我們來看一道題:

代碼1:

def foo():
  return [lambda x: x**i for i in range(1,5,2)]
print([f(3) for f in foo()])

伙伴們,你們認為這里產生的結果是什么呢?我們再來看下這題的變體:

代碼:2

def foo():
  functions=[]
  for i in range(1,5,2):
    def inside_fun(x):
      return x ** i
    functions.append(inside_fun)
  return functions
print([f(3) for f in foo()])

這兩題的結果是一樣的:都是[27,27]。我相信大部分的伙伴也都會有個疑問,為什么不是[3,27]呢?

這里的就是我們今天要說的for循環(huán)中的變量作用域,因為for循環(huán)不是一個函數體,所以for循環(huán)中的變量i的作用域其實和for循環(huán)同級,即類似下面代碼

代碼3:

def foo():
  i=None
  for i in range(1,5,2):
    pass
  print(i)
foo() # 結果為3,即循環(huán)結束i的最終值

另外因為python運行到代碼行時才會去查找該變量的作用域,所以代碼1和代碼2中的i值在調用的時候為for循環(huán)最終值3,所以結果都是執(zhí)行x**3。

ps:下面看下python中for循環(huán)的用法

Python for循環(huán)可以遍歷任何序列的項目,如一個列表或者一個字符串。

語法模式:for iterating_var in sequence:

in 字面意思,從某個集合(列表等)里順次取值

#遍歷數字序列
the_count=[1,2,3,4,5]
for number in the_count:
  print(f"This is count {number}")
輸出結果:
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5 
#遍歷一維字符串數組
fruits=['apples','oranges','dimes','quarters']
for fruit in fruits:
  print(f"A fruit of type:{fruit}")
輸出結果為:
A fruit of type:apples
A fruit of type:oranges
A fruit of type:dimes
A fruit of type:quarters
#遍歷字符串
list_python='python'
for j in list_python:
  print(f"{j}")
輸出結果為:
p
y
t
h
o
n
#通過序列索引迭代
elements=[]#列表為空
for i in range(0,6):#012345
  print(f"Adding {i} to the list.")
  elements.append(i)#得到elements=[0,1,2,3,4,5]
  #len(elements)長為6,range(len(elements))==range(6)
for i in range(len(elements)):
  print(f"Elemnet was:{i}")
輸出結果為:
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Elemnet was:0
Elemnet was:1
Elemnet was:2
Elemnet was:3
Elemnet was:4
Elemnet was:5

總結

以上所述是小編給大家介紹的python中for循環(huán)變量作用域及用法詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI