社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

d789w • 7 年前 • 2064 次点击  

我想从下面的字符串元素中提取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]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39367
文章 [ 5 ]  |  最新文章 7 年前
AnswerSeeker
Reply   •   1 楼
AnswerSeeker    7 年前

代码:

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

输出:

[25, 1, 4, 101]

说明:

re.findall 返回从左到右扫描字符串的字符串列表,按找到的顺序返回匹配项。

map 对字符串列表中的每个项应用int并返回map对象

list 因为map对象是迭代器,所以将其作为参数传递给工厂方法以创建列表

awakenedhaki
Reply   •   2 楼
awakenedhaki    7 年前

您可以使用以下函数来实现这一点。我用过 re.compile 考虑到它比呼叫快一点 re 如果您有很长的列表,则直接从模块中输出函数。

我也用过 yield 和 finditer 因为我不知道你的列表会有多长时间,所以考虑到他们懒惰的评估,这会提供一些内存效率。

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]
Arkistarvh Kltzuonstev
Reply   •   3 楼
Arkistarvh Kltzuonstev    7 年前

试试这个:

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

产量 :

[25, 1, 4, 101]

另外,避免将变量名指定为 list .

AngusWR
Reply   •   4 楼
AngusWR    7 年前

我们不需要使用regex从字符串中获取数字。

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]
Shep
Reply   •   5 楼
Shep    7 年前

你错过了一个+

你发现所有人都应该有“\d+”,而不仅仅是“\d”