Python中整數字符串轉換為列表


整數字符串是指包含在雙引號內的任何數字,而整數列表定義為用逗號分隔的數字列表。在Python中,我們有一些內建函式——len()、isdigit()、append()、map()、fromstring()和split()——將用於整數字符串到列表的轉換。

例如

給定的整數字符串:

my_str = “1 2 3 4 5”

最終輸出為 [1, 2, 3, 4, 5]

語法

以下語法在示例中使用:

len()

len()是Python中的內建方法,返回物件的長度。

isdigit()

isdigit()是Python中的內建函式,如果所有字元都滿足數字條件,則返回true,否則返回false。

append()

append()是Python中的內建函式,它在列表末尾新增元素。

map()

內建函式map()允許為每個元素迭代應用特定函式。

fromstring()

fromstring()使用名為numpy的模組來建立一維陣列,其中陣列字串包含資料。

split()

split()是Python中的內建方法,它將字串以列表的形式分隔。

使用while迴圈

在下面的示例中,我們將使用while迴圈,該迴圈使用一些內建函式和運算子根據特定條件迭代輸入字串,並使用+=運算子用逗號(,)分隔整數字符串以獲得整數列表。

示例

str_int = '14 15 17 18'
lst_int = []
i = 0
while i < len(str_int):
    if str_int[i].isdigit():
        num = ''
        while i < len(str_int) and (str_int[i].isdigit() or str_int[i] == '-'):
            num += str_int[i]
            i += 1
        lst_int.append(int(num))
    else:
        i += 1
print("Conversion of integer string into integer list:", lst_int)

輸出

 Conversion of integer list into list: [14, 15, 17, 18]

使用map()和split()函式

在下面的示例中,程式首先初始化輸入字串。然後使用一些內建函式,如list()、map()和split()來計算整數字符串到整數列表的轉換並獲得結果。

示例

int_str = "1 2 3 4 5"
res = list(map(int, int_str.split()))
print("Conversion of integer string into integer list:", res)

輸出

Conversion of integer string into integer list: [1, 2, 3, 4, 5]

使用列表推導式

在下面的示例中,程式首先將整數字符串儲存在變數int_str中。然後使用列表推導式,其中變數i使用for迴圈遍歷給定的輸入字串int_str,並將其儲存在變數lst_int中。顯示結果。

示例

int_str = '4573'
lst_int = [int(i) for i in int_str]
print("Conversion of integer string into integer list:", lst_int)

輸出

 Conversion of integer string into integer list: [4, 5, 7, 3]

使用numpy模組

在下面的示例中,我們將首先匯入名為numpy的模組。然後將整數字符串儲存在變數str_int中。接下來,使用內建函式fromstring(),它接受三個引數——str_int(給定的輸入)、dtype(使用關鍵字int指定值為整數)、sep(資料中的分隔符),所有這些過程都將其儲存在變數res_list中。最後,我們使用名為res_list的變數列印結果。

示例

import numpy as np
str_int = '11 16 17 14 89'
res_list = np.fromstring(str_int, dtype=int, sep=' ').tolist()
print("Conversion of integer string into integer list:", res_list)

輸出

 Conversion of integer string into integer list: [11, 16, 17, 14, 89]

使用for迴圈

在下面的示例中,程式使用for迴圈結合內建函式split()迭代輸入字串。使用append(),它將在列表末尾新增元素。最後,顯示結果。

示例

str_int = '20 40 61 82 10'
lst_integers = []
for item in str_int.split(' '):
    lst_integers.append(int(item))
print("Conversion of integer string into integer list:", lst_integers)

輸出

 Conversion of integer string into integer list: [20, 40, 61, 82, 10]

結論

我們討論了將整數字符串轉換為整數列表的各種方法。這是一個重要的操作,它使用各種內建函式,如isdigit()、append()等,來執行特定任務。此程式通常用於某些應用程式,例如演算法問題解決、輸入驗證和資料預處理。

更新於:2023年8月14日

403 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.