python-3.x 如何在字典中就地更改值列表中的值

628mspwn  于 2022-12-24  发布在  Python
关注(0)|答案(4)|浏览(129)

如何替换值列表中的值?从float到int.
第一个月
结果:
some_dict = {"B1": [-1, 3], "B2": [-2, 4], "B3": [-3, 5], "B4": [-5, -6]}

jaxagkaj

jaxagkaj1#

我试试看:

{k: [int(v[0]), int(v[1])] for k, v in some_dict.items()}
bkhjykvo

bkhjykvo2#

我的意见是只需要迭代dict项,然后迭代values列表:

for key, value in some_dict.items():
    for i in range(len(value)):
        value[i] = int(value[i])
7kqas0il

7kqas0il3#

我想这会有用的

new_dict = {k: [int(i) for i in v] for k, v in some_dict.items()}
mkshixfv

mkshixfv4#

    • 答案:**
some_dict = {k: [int(vi) for vi in v] for k, v in some_dict.items()}
    • 测试**

测试代码:

some_dict = {"B1": [-1.0, 3.0], "B2": [-2.0, 4.0], "B3": [-3.0, 5.0], "B4": [-5, -6]}
print('some_dict = {}'.format(some_dict))

some_dict = {k: [int(vi) for vi in v] for k, v in some_dict.items()}
print('some_dict = {}'.format(some_dict))

输出:

some_dict = {'B1': [-1.0, 3.0], 'B2': [-2.0, 4.0], 'B3': [-3.0, 5.0], 'B4': [-5, -6]}
some_dict = {'B1': [-1, 3], 'B2': [-2, 4], 'B3': [-3, 5], 'B4': [-5, -6]}

相关问题