簡體   English   中英

在 Python 的 for 循環中使用多個變量

[英]Using multiple variables in a for loop in Python

我試圖更深入地了解 Python 中不同數據類型的for循環。 使用 for 循環迭代數組的最簡單方法是

for i in range(len(array)):
    do_something(array[i])

我也知道我可以

for i in array:
    do_something(i)

我想知道的是這是做什么的

for i, j in range(len(array)):
    # What is i and j here?

或者

for i, j in array:
    # What is i and j in this case?

如果我嘗試對dicttuples使用相同的想法會發生什么?

最簡單最好的方法是第二種,而不是第一種!

for i in array:
    do_something(i)

永遠不要這樣做,它不必要地使代碼復雜化:

for i in range(len(array)):
    do_something(array[i])

如果出於某種原因需要數組中的索引(通常不需要),請改為執行以下操作:

for i, element in enumerate(array):
    print("working with index", i)
    do_something(element)

這只是一個錯誤,你會得到TypeError: 'int' object is not iterable試圖將一個整數解壓縮成兩個名稱時:

for i, j in range(len(array)):
    # What is i and j here?

這個可能有效,假設數組是“二維的”:

for i, j in array:
    # What is i and j in this case?

二維數組的一個示例是一對列表:

>>> for i, j in [(0, 1), ('a', 'b')]:
...     print('i:', i, 'j:', j)
...     
i: 0 j: 1
i: a j: b

注意: ['these', 'structures']在 Python 中稱為列表,而不是數組。

您的第三個循環將不起作用,因為它會為int not being iterable拋出TypeError 這是因為您正試圖將作為數組索引的 int“ unpack ”到i中,而j這是不可能的。 拆包的一個例子是這樣的:

tup = (1,2)
a,b = tup

您將a指定為tuple中的第一個值,將b指定為第二個值。 當你可能有一個function返回一個值的元組並且你想在調用函數時立即解包它們時,這也很有用。 喜歡,

train_X, train_Y, validate_X, validate_Y = make_data(data)

我相信您所指的更常見的循環案例是如何遍歷數組項及其索引。

for i, e in enumerate(array):
    ...

for k,v in d.items():  
    ...

遍歷dictionary中的項目時。 此外,如果您有兩個列表l1l2您可以像這樣遍歷這兩個內容

for e1, e2 in zip(l1,l2):
    ...

請注意,在迭代時長度不等的情況下,這將截斷較長的列表。 或者說您有一個列表列表,其中外部列表​​的長度為m ,內部的長度為n ,您寧願遍歷按索引分組在一起的內部 lits 中的元素。 這有效地迭代了矩陣的轉置,您也可以使用 zip 來執行此操作。

for inner_joined in zip(*matrix):  # will run m times
    # len(inner_joined) == m
    ...

Python 的 for 循環是一個基於迭代器的循環(這就是為什么bruno desthuilliers說它“適用於所有可迭代對象(列表、元組、集合、字典、迭代器、生成器等)”。字符串也是另一種常見的可迭代對象)。

假設您有一個元組列表。 使用您共享的命名法,可以同時遍歷鍵和值。 例如:

tuple_list = [(1, "Countries, Cities and Villages"),(2,"Animals"),(3, "Objects")]

for k, v in tuple_list:
    print(k, v)

會給你輸出:

1 Countries, Cities and Villages
2 Animals
3 Objects

如果你使用字典,你也將能夠做到這一點。 這里的區別是需要 .items()

dictionary = {1: "Countries, Cities and Villages", 2: "Animals", 3: "Objects"}

for k, v in dictionary.items():
    print(k, v)

dictionary 和 dictionary.items() 的區別如下

dictionary: {1: 'Countries, Cities and Villages', 2: 'Animals', 3: 'Objects'}
dictionary.items(): dict_items([(1, 'Countries, Cities and Villages'), (2, 'Animals'), (3, 'Objects')])

使用 dictionary.items() 我們將獲得一個包含字典的鍵值對的視圖對象,作為列表中的元組。 換句話說,使用 dictionary.items() 您還將獲得一個元組列表。 如果你不使用它,你會得到

TypeError:無法解壓不可迭代的 int 對象

如果您想使用簡單列表獲得相同的輸出,則必須使用類似 enumerate()

list = ["Countries, Cities and Villages","Animals", "Objects"]

for k, v in enumerate(list, 1): # 1 means that I want to start from 1 instead of 0
    print(k, v)

如果你不這樣做,你會得到

ValueError:要解包的值太多(預期為 2)

所以,這自然提出了一個問題......我是否總是需要一個元組列表? 不,使用 enumerate() 我們會得到一個 enumerate 對象。

實際上,“使用for循環迭代數組的最簡單方法”(Python類型被命名為“list”BTW)是第二種,即

for item in somelist:
    do_something_with(item)

FWIW 適用於所有可迭代對象(列表、元組、集合、字典、迭代器、生成器等)。

基於范圍的 C 風格版本被認為是高度非 Python 化的,並且僅適用於列表或類似列表的可迭代對象。

我想知道的是這是做什么的

for i, j in range(len(array)):
    # What is i and j here?

好吧,你可以自己測試一下……但結果很明顯:它會引發TypeError ,因為解包只適用於可迭代對象,而整數不可迭代。

或者

for i, j in array:
    # What is i and j in this case?

取決於什么是array以及迭代它時產生的結果。 如果它是 2 元組列表或產生 2 元組的迭代器,則ij將是當前迭代項的元素,即:

array = [(letter, ord(letter)) for letter in "abcdef"]
for letter, letter_ord in array:
    print("{} : {}".format(letter, letter_ord))

否則,它很可能也會引發 TypeError。

請注意,如果您想要同時擁有項目和索引,則解決方案是內置enumerate(sequence) ,它為每個項目生成一個(index, item)元組:

array = list("abcdef")
for index, letter in enumerate(array):
    print("{} : {}".format(index, letter)

我只是想補充一點,即使在 Python 中,您也可以通過使用局部變量來使用經典的 C 樣式循環來實現for in

l = len(mylist) #I often need to use this more than once anyways

for n in range(l-1):
    i = mylist[n]
    
    print("iterator:",n, " item:",i)

理解了您的問題,並使用不同的示例對其進行了解釋。

1. 使用 -> Dictionary 進行多重賦值

dict1 = {1: "Bitcoin", 2: "Ethereum"}

for key, value in dict1.items():
    print(f"Key {key} has value {value}")

print(dict1.items())

輸出:

Key 1 has value Bitcoin
Key 2 has value Ethereum
dict_items([(1, 'Bitcoin'), (2, 'Ethereum')])

解釋dict1.items()

dict1_items()創建值dict_items([(1, 'Bitcoin'), (2, 'Ethereum')])

每次迭代都成對出現(鍵,值)。

2. 使用 -> enumerate() 函數進行多重賦值

coins = ["Bitcoin", "Ethereum", "Cardano"]
prices = [48000, 2585, 2]
for i, coin in enumerate(coins):
    price = prices[i]
    print(f"${price} for 1 {coin}")

輸出:

$48000 for 1 Bitcoin
$2585 for 1 Ethereum
$2 for 1 Cardano

解釋enumerate(coins)

enumerate(coins)創造價值((0, 'Bitcoin'), (1, 'Ethereum'), (2, 'Cardano'))

對於每個(一次)迭代,它成對出現(索引,值)

3. 使用 -> zip() 函數進行多重賦值

coins = ["Bitcoin", "Ethereum", "Cardano"]
prices = [48000, 2585, 2]
for coin, price in zip(coins, prices):
    print(f"${price} for 1 {coin}")

輸出:

$48000 for 1 Bitcoin
$2585 for 1 Ethereum
$2 for 1 Cardano

解釋

zip(coins, prices)創造價值(('Bitcoin', 48000), ('Ethereum', 2585), ('Cardano', 2))

對於每個(一個)迭代,它成對出現(value-list1, value-list2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM