从字典中删除特定的字符串

时间:2019-04-29 11:11:50

标签: python python-3.x dictionary string-formatting

我有一本这种格式的字典

Open = {'22.0x7.5x8.0 12.0': ['4.60x4.30x4.30 13.00, 4.60x4.30x4.30 1.00, 
                              4.60x4.30x4.30 2.00, 6.60x6.00x5.16 5.00'], 
         '18.0x7.0x7.0 7.0': ['4.60x4.30x4.30 1.00, 8.75x6.60x5.60 4.00'],
           '22.0x7.5x8.0 9.0': ['6.60x6.00x5.16 5.00, 6.60x6.00x5.16 9.00, 
                                6.60x6.00x5.16 5.00']}

我想从键和值中删除尺寸part(1x2x3)并将其余部分转换为整数。我该怎么办?

这样我的输出就是这样

new = {12:[13,1,2,5],
          7:[1,4]...}

2 个答案:

答案 0 :(得分:2)

使用str.split应该足够了。

Open = {'22.0x7.5x8.0 12.0': ['4.60x4.30x4.30 13.00, 4.60x4.30x4.30 1.00',
                              '4.60x4.30x4.30 2.00, 6.60x6.00x5.16 5.00'],
         '18.0x7.0x7.0 7.0': ['4.60x4.30x4.30 1.00, 8.75x6.60x5.60 4.00'],
           '22.0x7.5x8.0 9.0': ['6.60x6.00x5.16 5.00, 6.60x6.00x5.16 9.00',
                                '6.60x6.00x5.16 5.00']}

res = {}
for key,value in Open.items():

    #Split on space and convert to int for key
    k = int(float(key.split()[1]))
    li = []
    for v in value:
        #First split on comma
        for i in v.split(','):
            #Then split on space
            num = int(float(i.split()[1]))
            #Append the number to a list
            li.append(num)
    #Assign the list to the key
    res[k] = li

print(res)

输出将为

{12: [13, 1, 2, 5], 7: [1, 4], 9: [5, 9, 5]}

答案 1 :(得分:1)

使用str.split

例如:

Open = {'18.0x7.0x7.0 7.0': ['4.60x4.30x4.30 1.00, 8.75x6.60x5.60 4.00'], '22.0x7.5x8.0 12.0': ['4.60x4.30x4.30 13.00, 4.60x4.30x4.30 1.00, 4.60x4.30x4.30 2.00, 6.60x6.00x5.16 5.00'], '22.0x7.5x8.0 9.0': ['6.60x6.00x5.16 5.00, 6.60x6.00x5.16 9.00,6.60x6.00x5.16 5.00']}

print({float(k.split()[1]): [float(j.split()[1]) for i in v for j in i.split(",")] for k,v in Open.items()})
#Or
#print({int(float(k.split()[1])): [int(float(j.split()[1])) for i in v for j in i.split(",")] for k,v in Open.items()})

输出:

{9.0: [5.0, 9.0, 5.0], 12.0: [13.0, 1.0, 2.0, 5.0], 7.0: [1.0, 4.0]}