基本上,我想从字符串列表中创建一个数值列表。我编写了一个简单的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?
您忘记在每次迭代后将“foo”重置为0
试试这个:
使用正则表达式
re.match
Ex:
通过使用
for
循环和列表理解而不是while
,可以大大简化代码相关问题 更多 >
编程相关推荐