Python程式將整數列表轉換為字串列表


在Python中,列表是可儲存多個值的專案或元素的集合。它是Python的內建資料型別之一,通常用於儲存和組織資料。

列表用方括號[]表示,列表中的元素用逗號分隔。元素可以是任何資料型別,包括數字、字串、布林值,甚至其他列表。列表是可變的,這意味著您可以修改、新增或刪除其中的元素。

將整數列表轉換為字串列表涉及將每個整數元素轉換為其字串表示形式。在本文中,我們將看到使用Python程式設計將整數列表轉換為字串列表的不同方法。

輸入輸出場景

讓我們透過一些輸入輸出場景來了解將整數列表轉換為字串列表的過程。

Input: [1, 2, 3, 4, 5]
Output: ['1', '2', '3', '4', '5']

讓我們探索不同的方法。

使用for迴圈

此方法使用for迴圈迭代列表中的整數。在迴圈中,每個整數都使用str()函式轉換為字串,然後將生成的字串追加到新列表中。

示例

這是一個使用for迴圈將整數列表轉換為字串列表的示例。

# Define the input list
integer_list = [9, 3, 0, 1, 6, 4, 9]
print('Input list of integers:', integer_list)

# Convert using a for loop
string_list = []
for num in integer_list:
    string_list.append(str(num))
    
# Display the output
print('Output list of strings:', string_list)

輸出

Input list of integers: [9, 3, 0, 1, 6, 4, 9]
Output list of strings: ['9', '3', '0', '1', '6', '4', '9']

使用列表推導式

此方法類似於前一個方法,但它提供了使用列表推導式的便利。列表推導式允許使用更簡潔和簡化的程式碼將整數轉換為字串並生成新列表。

示例

這是一個使用列表推導式的示例。

# Define the input list
integer_list = [1, 2, 3, 4, 5]
print('Input list of integers:', integer_list)

# Convert using the List Comprehension
string_list = [str(num) for num in integer_list]

# Display the output
print('Output list of strings:', string_list)

輸出

Input list of integers: [1, 2, 3, 4, 5]
Output list of strings: ['1', '2', '3', '4', '5']

使用map()函式

map()函式可用於將str()函式應用於列表中的每個整數。map()函式返回一個迭代器,因此有必要使用list()將其轉換為列表。

示例

這是一個使用map()函式的示例。

# Define the input list
integer_list = [4, 3, 5, 4, 8, 9, 4]
print('Input list of integers:', integer_list)

# Convert using the map() function
string_list = list(map(str, integer_list))

# Display the output
print('Output list of strings:', string_list)

輸出

Input list of integers: [4, 3, 5, 4, 8, 9, 4]
Output list of strings: ['4', '3', '5', '4', '8', '9', '4']

使用format()函式

Python format()函式允許使用各種格式選項將值格式化為字串。當format()函式與“d”格式說明符一起使用時,它專門用於格式化整數值。

示例

這是一個使用帶有“d”格式說明符的format()的示例。

# Define the input list
integer_list = [6, 7, 0, 1, 6, 2, 4]
print('Input list of integers:', integer_list)

# Convert using the format() function
string_list = [format(num, 'd') for num in integer_list]
    
# Display the output
print('Output list of strings:', string_list)

輸出

Input list of integers: [6, 7, 0, 1, 6, 2, 4]
Output list of strings: ['6', '7', '0', '1', '6', '2', '4']

這些是使用Python程式設計將整數列表轉換為字串列表的幾種不同方法。

更新於: 2023年8月29日

745 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.