将字典的字符串转换为int

时间:2019-05-10 07:56:54

标签: python python-3.x dictionary

我已加载词典:

{'17.0x6.0x7.0 6.0': ['4.60x4.30x4.30 4.00, 4.60x4.30x4.30 1.00, 4.60x4.30x4.30 3.00'],
 '9.5x5.5x5.5 1.0': ['4.60x4.30x4.30 5.00'],
 '22.0x7.5x8.0 10.0': ['6.60x6.00x5.16 8.00, 9.00x6.00x5.60 6.00'],
 '17.0x6.0x7.0 6.0_1': ['8.75x6.60x5.60 7.00'],
 '9.5x5.5x5.5 2.0': ['4.60x4.30x4.30 2.00']}

我想提取尺寸后的浮点值

所需的输出:

{6:[4,1,3],
 1:[5],
 10:[8,6],
 6:[7]
 2:[2]}

我尝试过提取尺寸

loaded_items = {int(float(k.split()[1])): [int(float(j.split()[1])) for i in v for j in i.split(",")] for k,v in loaded.items()}

但这给了我这样的输出:

{6: [7], 1: [5], 10: [8, 6], 2: [2]}

即,当遇到第二个相似的对象时,它将替换该值。

我尝试了另一种方法:

all_items_loaded = {}
for k,v in loaded.items():
    a = k.split()[1]
    print(a)
    for i in v:
        x = i.split()
        x = x[1::2]
        all_items_loaded[a] = x

,输出为:

{'6.0': ['4.00,', '1.00,', '3.00'],
 '1.0': ['5.00'],
 '10.0': ['8.00,', '6.00'],
 '6.0_1': ['7.00'],
 '2.0': ['2.00']}

3 个答案:

答案 0 :(得分:2)

您的数据和所需的输出存在问题。

输入字典包含键“ 17.0x6.0x7.0 6.0_1 ”。在对“ 6.0_1”调用int(float())时,该方法有效(将其强制转换为6.01,然后转换为6),我不建议这样做,而是调查以这种方式提供此数据的原因。

所需的输出字典包含重复的键。这是不可能的,并且会导致您描述的书写。将输出数据结构从dict更改为例如字典列表。

[{int(float(key.split()[1])): [int(float(val.split()[1])) for val in value[0].split(",")]} for (key,value) in a.items() ]
--> [{6: [4, 1, 3]}, {1: [5]}, {10: [8, 6]}, {6: [7]}, {2: [2]}]

答案 1 :(得分:0)

您需要确定关联数据的其他方式,或者选择要使用的其他数据结构。下面是一个示例defaultdict。这不是不是唯一的解决方案,获得更好的输入将是第一要务。

from collections import defaultdict

d = defaultdict(list)
d['6.0'].append([7])
d['6.0'].append([4,1,3])

print(d['6.0'])

# result [[7], [4, 1, 3]]

答案 2 :(得分:0)

我唯一能提出的建议(除了获得更好的输入)是创建元组。创建一个简单的函数以从字符串中提取值:

>>> def extract(v): return int(float(v.split()[1]))

并将此函数应用于字典键值对并生成对列表:

>>> loaded_items = {
...     '17.0x6.0x7.0 6.0': ['4.60x4.30x4.30 4.00, 4.60x4.30x4.30 1.00, 4.60x4.30x4.30 3.00'],
...     '9.5x5.5x5.5 1.0': ['4.60x4.30x4.30 5.00'],
...     '22.0x7.5x8.0 10.0': ['6.60x6.00x5.16 8.00, 9.00x6.00x5.60 6.00'],
...     '17.0x6.0x7.0 6.0_1': ['8.75x6.60x5.60 7.00'],
...     '9.5x5.5x5.5 2.0': ['4.60x4.30x4.30 2.00']
... }
>>> data = [(extract(k), [extract(v) for v in vs[0].split(",")])  for k, vs in loaded_items.items()]
>>> data
[(6, [4, 1, 3]), (1, [5]), (10, [8, 6]), (6, [7]), (2, [2])]

然后可以根据需要将值分组:

>>> d1 = {}
>>> for k,v in data: d1.setdefault(k, []).extend(v)
>>> d1
{6: [4, 1, 3, 7], 1: [5], 10: [8, 6], 2: [2]}

或者:

>>> d2 = {}
>>> for k,v in data: d2.setdefault(k, []).append(v)
>>> d2
{6: [[4, 1, 3], [7]], 1: [[5]], 10: [[8, 6]], 2: [[2]]}