如何在此列表列表中将字符串转换为十进制?

How to convert string to decimal in this list of lists?

我正在尝试将此列表列表中的字符串转换为十进制形式:

ask = [['31188.28758860', 2], ['31183.48445986', 0.14258435], ...]

我尝试使用 elem.strip('"') for elem in ask 删除引号但得到“AttributeError: 'list' object has no attribute 'strip'” 所以我假设我没有访问的嵌套级别字符串

试试这个:

ans = [[float(i) if type(i)==str else i  for i in j] for j in ask]
print(ans)

输出

[[31188.2875886, 2], [31183.48445986, 0.14258435]]
ask = [['31188.28758860', 2], ['31183.48445986', 0.14258435], ...]

converted_ask = [[float(x[0]), x[1]] for x in ask]
[float(elem[0]) for elem in ask]

只获取嵌套列表的第一个值。

[[float(elem[0]), elem[1]] for elem in ask]

获得与以前相同的结构,但字符串替换为浮点数。

ask = [['31188.28758860', 2], ['31183.48445986', 0.14258435]]
ask_list = [[float(j) for j in i] for i in ask]

这将完成您的工作。输出 (ask_list) 将是 [[31188.2875886, 2.0], [31183.48445986, 0.14258435]].