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?
解决方案
使用正则表达式。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']
推荐阅读
- php - How add "Add new" option of the custom post types in plugin menus?
- java - How to resolve exception in paytm checksum generation using java
- javascript - Cannot find post paramaters in php
- java - 休眠搜索,过滤高于其他过滤器
- angular - Google analytics - Avg page load for Angular 5
- redis - 带有 Redis 数据的样本的 JMeter 顺序
- .net - 域外用户访问的公司应用是否需要开启ADFS?
- css - 如何在 Bootstrap NgbTypeahead 中使用向上和向下箭头键滚动
- sql - 更新受组影响的所有行
- bash - 在 bash 中定义一个函数并将其传递给 .run 脚本