Python 程式建立以零為中心的列表
建立以零為中心的列表涉及生成一個數字序列,其中零位於列表的中間。雖然列表的大小可以自定義,但通常建議使用奇數以確保元素圍繞零的對稱分佈。
在本文中,我們將討論使用 Python 程式設計建立以零為中心的列表的不同方法。
方法
我們可以按照以下步驟建立以零為中心的列表:
確定所需的列表大小。我們將其值稱為 n。
如果 n 是奇數,則它已經適合建立以零為中心的列表。如果 n 是偶數,我們需要將其調整到下一個奇數,以確保零位於中心。
透過對 n 執行整數除法 (//) 2 來計算列表的半大小。此值表示零兩側的元素數量。
使用 range 函式建立一個列表,從 -half 開始到 half + 1 結束。該範圍將生成從 -half 到 half(包括)的數字。透過將 1 加到 half,我們確保零包含在列表中。
使用 list 函式將 range 物件轉換為列表。
透過遵循這些步驟,我們確保列表中的值將圍繞零對稱分佈。
輸入-輸出場景
讓我們瞭解一些輸入-輸出場景
Input integer = 5 Output centered list [-2, -1, 0, 1, 2]
輸入大小整數為奇數,因此輸出列表建立的元素範圍為 -2 到 2,以零為中心。
Input integer = 6 Output centered list [-3, -2, -1, 0, 1, 2, 3]
輸入大小為偶數,輸出列表建立的元素(調整到下一個奇數 7)範圍為 -3 到 3,以零為中心。
使用 range() 函式
在這種方法中,我們利用 **range()** 函式生成一個表示以零為中心的列表的數字序列。列表的半大小是透過使用向下取整運算子 (//) 將 n 除以 2 來確定的。透過在範圍內從 -half 開始到 half + 1 結束,我們確保生成的列表以零為中心。為了將 range 物件轉換為列表,我們應用 list() 函式。
示例
在此示例中,我們將定義一個函式,該函式以整數作為輸入,並根據該值建立一個以零為中心的列表。
def create_centered_list(n): if n % 2 == 0: # If n is even, we adjust it to the next odd number n += 1 half = n // 2 centered_list = list(range(-half, half + 1)) return centered_list # define the size of the centered list size = 9 centered_list = create_centered_list(size) print('Output centered list:',centered_list)
輸出
Output centered list: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
示例
此示例與上一個示例的工作方式類似,但此處不使用 list() 函式,而是使用列表推導式將 range 物件轉換為列表。
def create_centered_list(n): if n % 2 == 0: # If n is even, we adjust it to the next odd number n += 1 half = n // 2 centered_list = [x for x in range(-half, half + 1)] return centered_list # define the size of the centered list size = 15 centered_list = create_centered_list(size) print('Output centered list:',centered_list)
輸出
Output centered list: [-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
使用 np.arange() 函式
在這裡,NumPy 庫中的 np.arange() 函式用於建立具有指定起始、停止和步長大小的數字序列。
示例
在此示例中,使用 numpy 庫建立以零為中心的列表。
import numpy as np def create_centered_list(n): if n % 2 == 0: # If n is even, we adjust it to the next odd number n += 1 half = n // 2 centered_list = np.arange(-half, half + 1) return centered_list.tolist() # define the size of the centered list size = 4 centered_list = create_centered_list(size) print('Output centered list:',centered_list)
輸出
Output centered list: [-2, -1, 0, 1, 2]