问题
If I were to have the following list:
lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
how would I convert all possible items into either ints or floats accordingly, to get
lst = [3, 7, 'foo', 2.6, 'bar', 8.9]
thanks in advance.
回答1:
Loop over each item and make an attempt to convert. If the conversion fail then you know it's not convertible.
def tryconvert(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return s
lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
newlst = [tryconvert(i) for i in lst]
print(newlst)
Output:
[3, 7, 'foo', 2.6, 'bar', 8.9]
回答2:
Try something like this :
lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
for j,i in enumerate(lst):
if i.isdigit():
lst[j]=int(i)
elif '.' in i:
lst[j]=float(i)
output:
[3, 7, 'foo', 2.6, 'bar', 8.9]
来源:https://stackoverflow.com/questions/48441382/python-converting-strings-in-list-to-ints-and-floats