Python字典以满足所需用途的数据重排。

huangapple go评论69阅读模式
英文:

Python dict to reformat data for required use

问题

Here is the refactored version of your format_data_car(car_info) function:

def format_data_car(car_info):
    result = {}
    for car in car_info:
        drive_modes = car.get('drive_mode', [])
        for mode in drive_modes:
            if mode not in result:
                result[mode] = []
            result[mode].append(car['car'])
    return result

This refactored function simplifies the code and achieves the same output format as you specified.

英文:

I need an help in code refactoring i have written the code and works fine.
but i've been using lot of code to get his achieved

I am using Python 2.7 version.
Any input on this will be great.

# source data:
car_info =[
    {'car': 'benz1', 'drive_mode': ['electric']},
    {'car': 'benz2', 'drive_mode': ['electric']},
    {'car': 'benz3', 'drive_mode': ['electric']},
    {'car': 'benz4', 'drive_mode': ['petrol']},
    {'car': 'bmw1', 'drive_mode': ['petrol']},
    {'car': 'bmw2', 'drive_mode': ['petrol']},
    {'car': 'bmw3', 'drive_mode': ['petrol']},
    {'car': 'bmw3', 'drive_mode': []}
  ]

# output format needed:
{'electric': ['benz1', 'benz2', 'benz3'], 'petrol': ['benz4', 'bmw1', 'bmw2', 'bmw3']}

Code i have tired so far and working one.

from collections import defaultdict
# source data:
car_info =[
    {'car': 'benz1', 'drive_mode': ['electric']},
    {'car': 'benz2', 'drive_mode': ['electric']},
    {'car': 'benz3', 'drive_mode': ['electric']},
    {'car': 'benz4', 'drive_mode': ['petrol']},
    {'car': 'bmw1', 'drive_mode': ['petrol']},
    {'car': 'bmw2', 'drive_mode': ['petrol']},
    {'car': 'bmw3', 'drive_mode': ['petrol']},
  {'car': 'bmw3', 'drive_mode': []}
  ]



def format_data_car(car_info):
    car_data = []
    get_values_for_keys = ['car', 'drive_mode']
    for step_name in car_info:
        for key, val in step_name.items():
            step_id_values = dict(filter(lambda item: item[0] in get_values_for_keys, step_name.items())).values()
            car_data.append(step_id_values)
            break
    filter_data = {}
    format_steps_ids = dict(car_data)
    for key, value in format_steps_ids.items():
        filter_data[key] = str(value)[2:-2]
    print(filter_data)
    return filter_data


def testing(source_info):
 d = defaultdict(list)
 for k, v in source_info.items():
  d[v].append(k)
 print(dict(d))


print(testing(format_data_car(car_info)))

How can I refactor my code function: format_data_car(car_info)?

答案1

得分: 0

以下是翻译好的内容:

所有你真正需要做的就是循环遍历每辆车,然后对于每种驾驶模式,将该车添加到字典中相应驾驶模式的列表中。要做到这一点,你只需要一个简单的嵌套循环,并检查 drive_mode 是否为空:

import collections

def format_data(car_info):
    d = collections.defaultdict(list)
    for car in car_info:
        if not car['drive_mode']:
            d[''].append(car['car'])
        
        for drive_mode in car['drive_mode']:
            d[drive_mode].append(car['car'])
    return d
英文:

All you really need to do is loop over every car, then for each drive mode it has, add that car to the dictionary's list for that drive mode. To do this, all you need is a simple nested for-loop and check if the drive_mode is empty:

import collections


def format_data(car_info):
    d = collections.defaultdict(list)
    for car in car_info:
        if not car['drive_mode']:
            d[''].append(car['car'])
        
        for drive_mode in car['drive_mode']:
            d[drive_mode].append(car['car'])
    return d

huangapple
  • 本文由 发表于 2023年5月14日 22:09:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定