首页 > 解决方案 > 从字符串列表中创建仅包含数值的列表

问题描述

基本上,我想从字符串列表中创建一个数值列表。我编写了一个简单的 while 循环来检查列表中每个字符串中的每个字符,但它没有按预期返回。有没有更好的方法来做到这一点,还是我把事情搞砸了?这是我的代码:

textList = ["3", "2 string", "3FOO"]
newList = []
i= 0
foo = 0
while i < len(textList):
    tmplist=[]
    while foo < len(textList[i]):
        bar = textList[i]
        if bar[foo].isnumeric():
            tmplist.append(str(bar[foo]))
        foo += 1
    tmpstring = str(''.join(tmplist))
    newList.append(tmpstring)
    i += 1
print(newList)

预期的输出是

["3", "2", "3"]

但是,我得到:

["3", "", ""]

Can anyone explain why?

标签: pythonpython-3.xlistwhile-loop

解决方案


使用正则表达式。re.match

前任:

import re

textList = ["3", "2 string", "3FOO"]
newList = []
ptrn = re.compile(r"(\d+)")
for i in textList:
    m = ptrn.match(i)
    if m:
        newList.append(m.group(0))
print(newList)  # -->['3', '2', '3']

推荐阅读