[英]Convert a list of strings to either int or float
我有一个看起来像这样的列表:
['1', '2', '3.4', '5.6', '7.8']
如何将前两个更改为int
,最后三个更改为float
?
我希望我的列表看起来像这样:
[1, 2, 3.4, 5.6, 7.8]
>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [float(i) if '.' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8]
有趣的指数边缘情况。 您可以添加到条件。
>>> s = ['1', '2', '3.4', '5.6', '7.8' , '1e2']
>>> [float(i) if '.' in i or 'e' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]
使用isdigit
是最好的,因为它可以处理所有边缘情况( Steven在评论中提到)
>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [int(i) if i.isdigit() else float(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]
使用辅助函数:
def int_or_float(s):
try:
return int(s)
except ValueError:
return float(s)
然后使用list comprehension来应用函数:
[int_or_float(el) for el in lst]
为什么不使用ast.literal_eval
?
import ast
[ast.literal_eval(el) for el in lst]
应该处理所有角落案件。 对于这个用例来说,它有点重量级,但是如果你希望在列表中处理任何类似数字的字符串,那么这就行了。
使用字符串的isdigit方法:
numbers = [int(s) if s.isdigit() else float(s) for s in numbers]
或与地图:
numbers = map(lambda x: int(x) if x.isdigit() else float(x), numbers)
def st_t_onumber(x):
import numbers
# if any number
if isinstance(x,numbers.Number):
return x
# if non a number try convert string to float or it
for type_ in (int, float):
try:
return type_(x)
except ValueError:
continue
l = ['1', '2', '3.4', '5.6', '7.8']
li = [ st_t_onumber(x) for x in l]
print(li)
[1, 2, 3.4, 5.6, 7.8]
如果要显示为相同的列表,请使用以下查询追加列表:
item = input("Enter your Item to the List: ")
shopList.append(int(item) if item.isdigit() else float(item))
这里当用户输入int值或浮点值时,它会附加列表shopList并将这些值存储在其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.