首頁  >  文章  >  後端開發  >  為什麼 Python 的 `itertools.chain` 函數中的 Asterisk 會扁平化列表?

為什麼 Python 的 `itertools.chain` 函數中的 Asterisk 會扁平化列表?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-27 11:13:01788瀏覽

Why Does the Asterisk Flatten Lists in Python's `itertools.chain` Function?

Asterisk 運算子如何在 Python 中展平列表

在 Python 中,itertools.chain 函數可用於展平列表列表。下面的程式碼片段示範了這一點:

<code class="python">uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs))</code>

但是,您可能想知道為什麼函數呼叫包含星號 (*)。

了解星號運算子

星號在 Python 中稱為「splat」運算子。它接受一個可迭代物件(例如列表),並將其擴展為函數呼叫中的實際位置參數。

它是如何運作的

考慮以下範例,其中 uniqueCrossTabs 是清單清單:[[1, 2], [3, 4]]。當您使用星號時,itertools.chain(*uniqueCrossTabs) 將清單擴展為單獨的清單參數。這相當於呼叫 itertools.chain([1, 2], [3, 4])。

與不帶星號的比較

不帶星號,您將只傳入 uniqueCrossTabs 作為單一參數。在這種情況下,chain() 將傳回一個迭代器,該迭代器迭代列表列表,而不是單個元素。

使用 chain.from_iterable()

For展平列表,itertools.chain.from_iterable() 是更合適的選擇。它採用單一可迭代物件作為參數。使用這種方法,程式碼就變成:

<code class="python">uniqueCrossTabs = list(itertools.chain.from_iterable(uniqueCrossTabs))</code>

以上是為什麼 Python 的 `itertools.chain` 函數中的 Asterisk 會扁平化列表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn