如何将字符串中的数字作为 python 中的单个元素提取到列表中?

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.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 returns 字符串列表,其中字符串从左到右扫描,匹配项按找到的顺序 return。

map 将 int 应用于字符串列表中的每个项目和 returns 映射对象

list 由于 map 对象是迭代器,将其作为参数传递给用于创建列表的工厂方法