我有一个像 [2,3,4,"5cm", 6,"2.5km"] 这样的输入列表,我想要一个结果:
[2,3,4,5,6,2.5]
我想这样开始
for element in inputList:
请您参考如下方法:
您可以使用正则表达式:
>>> import re
>>> lis = [2,3,4,"5cm", 6,"2.5km"]
>>> r = re.compile(r'\d+(.\d+)?')
>>> [float(r.search(x).group(0)) if isinstance(x,str) else x for x in lis]
[2, 3, 4, 5.0, 6, 2.5]
使用 ast.literal_eval 而不是 float 得到 5.0 作为 5:
>>> from ast import literal_eval
>>> [literal_eval(r.search(x).group(0)) if isinstance(x,str) else x for x in lis]
[2, 3, 4, 5, 6, 2.5]
开始你的方式:
import re
from ast import literal_eval
ans = []
r = re.compile(r'\d+(.\d+)?') #regex to match an integer or decimal
inputList = [2,3,4,"5cm", 6,"2.5km"]
for element in inputList:
if isinstance(element, str): #if element is a string then apply the regex
num = r.search(element).group(0)
ans.append(literal_eval(num))
else:
ans.append(element) #else append the element as it is
print ans
#[2, 3, 4, 5, 6, 2.5]
另一种解决方案,考虑到您的输入始终有效:
>>> from string import digits
>>> allowed = '-+.' + digits
>>> allowed #allowed characters
'-+.0123456789'
>>> lis = [2,3,4,"5cm", 6,"2.5km"]
>>> ans = []
for item in lis:
if isinstance(item, str):
# if item is a string
num = '' # Initialize an empty string
for c in item: # Iterate over the string, one character at time.
if c in allowed: # If the character is present in `allowed` then
num += c # concatenate it to num
else:
break # else break out of loop
ans.append(float(num)) # Append the float() output of `num` to `ans` or use
# `ast.literal_eval`
else:
ans.append(item)
...
>>> ans
[2, 3, 4, 5.0, 6, 2.5]
