簡體   English   中英

如何將數字從字符串提取為列表中的單個元素?

[英]How can extract numbers from a string to a list as individual elements in python?

我想將以下n長度列表的字符串元素中的數字提取到其原始形式的列表中:

list = ['25 birds, 1 cat, 4 dogs, 101 ants']

output = [25, 1, 4, 101]

我對regex還是很陌生,所以我一直在嘗試以下方法:

[regex.findall("\d", list[i]) for i in range(len(list))]

但是,輸出為:

output = [2, 5, 1, 4, 1, 0, 1]

嘗試這個 :

list_ = ['25 birds, 1 cat, 4 dogs, 101 ants']
import re
list(map(int, re.findall('\d+', list_[0])))

輸出

[25, 1, 4, 101]

另外,避免將變量名稱分配為list

您錯過了+

您會發現所有人都應該有“ \\ d +”,而不僅僅是“ \\ d”

我們實際上並不需要使用正則表達式從字符串中獲取數字。

lst = ['25 birds, 1 cat, 4 dogs, 101 ants']
nums = [int(word) for item in lst for word in item.split() if word.isdigit()]
print(nums)
# [25, 1, 4, 101]

沒有列表理解的等效項:

lst = ['25 birds, 1 cat, 4 dogs, 101 ants']
nums = []
for item in lst:
    for word in item.split():
        if word.isdigit():
            nums.append(int(word))
print(nums)
# [25, 1, 4, 101]

您可以使用以下功能來實現。 我使用re.compile是因為它比直接在模塊中調用re函數要快一些(如果您的列表很長)。

我還使用了yieldfinditer因為我不知道您的列表將持續多久,因此,考慮到他們的懶惰評估,這將提供一定的存儲效率。

import re

def find_numbers(iterable):
    NUMBER = re.compile('\d+')
    def numbers():
        for string in iterable:
            yield from NUMBER.finditer(iterable)

    for number in numbers():
        yield int(number.group(0))

print(list(find_numbers(['25 birds, 1 cat, 4 dogs, 101 ants'])))
# [25, 1, 4, 101]

碼:

import re

list_ = ['25 birds, 1 cat, 4 dogs, 101 ants']
output = list(map(int, re.findall('\d+', list_[0])))
print(output)

輸出:

[25, 1, 4, 101]

說明:

re.findall返回字符串列表,其中從左到右掃描字符串,以找到的順序返回匹配項。

map將int應用於字符串列表中的每個項目,並返回map對象

list由於地圖對象是迭代器,請將其作為參數傳遞給用於創建列表的工廠方法

暫無
暫無

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

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