【问题标题】:Refactoring for loop containing nested lists/dictionary重构包含嵌套列表/字典的循环
【发布时间】:2022-01-08 09:23:34
【问题描述】:

问题:作为我一直在阅读的这本 Python 书籍中学习的一部分,其中一个挑战是重构之前挑战中的一些代码。挑战在于重构在列表“all_eq_data”上重复的循环,该列表包含从 JSON 文件加载到其中的数据。执行拉动的 for 循环使用 4 个变量(mags、lons、lats、title),但挑战指出这些变量不是必需的,并且循环可以减少到 4 行(我假设将数据加载到相应的列表中)。

所以,至少只是在寻找正确方向的推动力。在进入本书/项目的下一部分之前,我绝对想得到这个。谢谢你的帮助!!

    ...
    import json
    from plotly.graph_objs import scattergeo, Layout
    from plotly import offline

    # Explore the structure of the data.
    filename = 'data/eq_data_30_day_m1.json'
    with open(filename) as f:
        all_eq_data = json.load(f)
    
        all_eq_dicts = all_eq_data['features']
        # print(all_eq_dicts)
    
        eq_dict = []
    
    
    mags = [eq_dict['properties'] for 'mag' in all_eq_dicts]
    lons = [eq_dict['geometry']['coordinates'][0]  "lon" in all_eq_dicts]
    lats = [eq_dict['geometry']['coordinates'][1] in all_eq_dicts]
    hover_texts = [eq_dict['properties'] in all_eq_dicts]
    
    
    # --------------------------------------------------------------------------------------
# Using the for loop to iterate over the data; refactor loop to reduce lines of code.
    
    # mags, lons, lats, hover_texts = [], [], [], []
    for eq_dict in all_eq_dicts:
        mag = eq_dict['properties']['mag']
        lon = eq_dict['geometry']['coordinates'][0]
        lat = eq_dict['geometry']['coordinates'][1]
        title = eq_dict['properties']['title']
        
        mags.append(mag)
        lons.append(lon)
        lats.append(lat)
        hover_texts.append(title)
    # --------------------------------------------------------------------------------------
    
# Map the earthquakes.
    # Using a dictionary to plot the data and allow customization.
    data = [{
        'type': 'scattergeo',
        'lon': lons,
        'lat': lats,
        'text': hover_texts,
        'marker': {
            'size': [5*mag for mag in mags],
            'color': mags,
            'colorscale': 'Viridis',
            'reversescale': True,
            'colorbar': {'title': 'Magnitude'},
        },
    }]
    
# Visualize the data.
    my_layout = Layout(title='Global Earthquakes')
    
    fig = {'data': data, 'layout': my_layout}
    offline.plot(fig, filename='global_earthquakes.html')
...

【问题讨论】:

  • 您能否包括all_eq_dicts 是什么?
  • 变量只存储中间结果。您可以通过将结果直接放入列表中来避免它们:mags.append(eq_dict['properties']['mag']) - 这会将循环缩小到 4 行。 .... 但是 - 8 行完全没问题,可能比直接塞进去更易读。

标签: python loops refactoring


【解决方案1】:

这部分解决方案不起作用

mags = [eq_dict['properties'] for 'mag' in all_eq_dicts]
lons = [eq_dict['geometry']['coordinates'][0]  "lon" in all_eq_dicts]
lats = [eq_dict['geometry']['coordinates'][1] in all_eq_dicts]
hover_texts = [eq_dict['properties'] in all_eq_dicts]

因为 for 循环没有任何意义。您要做的就是用变量替换字符串。就叫它 eq_dict 就行了。

mags = [eq_dict['properties']['mag'] for eq_dict in all_eq_dicts]
lons = [eq_dict['geometry']['coordinates'][0]  for eq_dict in all_eq_dicts]
lats = [eq_dict['geometry']['coordinates'][1] for eq_dict in all_eq_dicts]
hover_texts = [eq_dict['properties']['title'] for eq_dict in all_eq_dicts]

【讨论】:

  • 我认为 magshover_texts 需要密钥,否则它们是相同的列表。
  • 真的,谢谢。我已经更新了。
猜你喜欢
  • 2014-05-11
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 2017-07-22
  • 2022-06-15
相关资源
最近更新 更多