如何生成 Python 字典同时将某些字符串转换为浮点数?

How to generate a Python dictionary with simultaneous converting certain strings to floats?

假设我在 matrix 变量中有 listlists

matrix = [['first', '1,1', 'last'], ['strng_1', '12231,71', 'st_2']]

如您所见,所有嵌套列表都将浮点数据写为字符串。我想将它们转换为 float 数据类型。 我需要创建一个字典并同时进行此转换。 出于这个原因,我尝试使用 dictionary comprehension 来实现它。因此,这些单行操作可能如下所示:

dict_comp = {r[0]: r.insert(1, float(r[1].replace(',', '.'))).pop(2) for r in matrix if r}

但它没有按预期工作。现在,在我 之后,我知道为什么了。 最后想问下如何生成同时将某些字符串转为浮点数的字典?

UPDATE

预期输出:

{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

以下将起作用:

dict_comp = {r[0]: [r[0], float(str(r[1]).replace(',','.')), r[2]] for r in matrix if r}

# {'first': ['first', 1.1, '1,1'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

根据我的回答

matrix = [['first', '1,1', 'last'], ['strng_1', '12231,71', 'st_2']]
[[r[0], float(r[1].replace(',', '.')), r[2]] for r in matrix]
# => [['first', 1.1, 'last'], ['strng_1', 12231.71, 'st_2']]

编辑:如果你想听写...

{r[0]: [r[0], float(r[1].replace(',', '.')), r[2]] for r in matrix}
# => {'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

您无法将 r.insert(1, float(r[1].replace(',', '.'))).pop(2) 保存为字典值。就像 None.pop(2) 会给你错误

根据您编辑的 @Carsten 的预期输出答案应该有效。

使用字典列表理解

例如

matrix = [['first', '1,1', 'last'], ['strng_1', '12231,71', 'st_2']]
new_list = {x[0]: [(float(i.replace(",",".")) if "," in i else i)for i in x ] for x in matrix}
print(new_list)

O/P:

{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

将其视为构建新列表而不是更改现有列表。

假设这是你想要使用字典理解来做的事情:

dict_ = {}
for row in matrix:
    new_row = row[:1] + [float(row[1].replace(',', '.'))] + row[2:]
    dict[row[0]] = new_row

这将被转换为:

dict_ = {r[0]: r[:1] + [float(r[1].replace(',', '.'))] + r[2:] for r in matrix if r}

不过,一般来说,我建议不要使用如此复杂的字典理解。它可能更短,但可读性较差。

将您的 locale 更改为可以将逗号理解为小数点的内容,例如 fr_FR.utf8,使用 locale.atof 将字符串转换为浮点数,然后恢复为您的语言环境

import locale 
loc = locale.getlocale() 
locale.setlocale(LC_NUMERIC, 'fr_FR.utf8')

d = {a:[a, locale.atof(b), c] for a,b,c in matrix}

locale.setlocale(LC_NUMERIC, loc)

print (d)

输出

{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

如果float字符串的位置总是相同的,可以在dict理解中使用解构赋值:

>>> matrix = [['first', '1,1', 'last'], ['strng_1', '12231,71', 'st_2']]
>>> {k: [k, float(f.replace(",", ".")), *l] for k, f, *l in matrix}
{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

如果浮动可能在除第一个以外的任何位置:

>>> def try_to_cast(v):
...    try:
...        return float(v.replace(",", "."))
...    except ValueError:
...        return v
...
>>> {k: [k, *[try_to_cast(v) for v in l]] for k, *l in matrix}
{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}

请参阅@Sunitha 的回答,了解使用 locale 将字符串转换为浮点数的更清晰的方法。