仅使用字符串列表中的数值创建列表

2024-09-27 23:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我想从字符串列表中创建一个数值列表。我编写了一个简单的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?

Tags: 方法字符串列表lenfoobar字符数值
3条回答

您忘记在每次迭代后将“foo”重置为0
试试这个:

textList = ["3", "2 string", "3FOO"]
newList = []
i= 0
while i < len(textList):
    tmplist=[]
    foo = 0
    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)

使用正则表达式re.match

Ex:

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']

通过使用for循环和列表理解而不是while,可以大大简化代码

textList = ["3", "2 string", "3FOO"]
newList = []
for s in textList:
    numlist = [c for c in s if c.isnumeric()]
    newList.append("".join(numlist))

相关问题 更多 >

    热门问题