【问题标题】:Combine two list as key value pair using zip if lists have same values如果列表具有相同的值,则使用 zip 将两个列表组合为键值对
【发布时间】:2018-07-21 15:34:45
【问题描述】:

我有两个列表:

yy = ['Inside the area', 'Inside the area', 'Inside the area', 'Inside the area', 'Inside the area', 'Inside the area', 'Outside the area']
lat_ = [77.2167, 77.25, 77.2167, 77.2167, 77.2, 77.2167, 77.2]

我正在使用以下一些帖子中给出的解决方案将它们组合起来:

new_dict = {k: v for k, v in zip(yy, lat_)}
print new_dict

但我的输出是{'Inside the area': 77.2167, 'Outside the area': 77.2}

发生这种情况是因为大多数键是相同的。我这样做是因为我想映射这两个列表以获取 lat 的哪些值落在内部或外部,然后只保留落在内部的值。

【问题讨论】:

  • 如果inside the area 键需要有很多值,你为什么要尝试使用字典?如果你仍然想,你可以为字典值创建列表,它可以为一个键保存多个值。
  • 但是问题是这样的:考虑当内部键映射到 77.216 并且同时外部键映射到相同值的情况。请注意,这两个列表都是两个不同函数的输出。这就是我不合并它的原因

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

您可以压缩它们并在列表理解中添加保护:

res = [lat for a, lat in zip(yy, lat_) if a.startswith(“Inside”)]

【讨论】:

    【解决方案2】:

    保留里面的值:

    代码:

    for k, v in zip(yy, lat_):
        if k.startswith('Inside'):
            inside.append(v)
    

    测试代码:

    yy = ['Inside the area', 'Inside the area', 'Inside the area',
          'Inside the area', 'Inside the area', 'Inside the area',
          'Outside the area']
    lat_ = [77.2167, 77.25, 77.2167, 77.2167, 77.2, 77.2167, 77.2]
    
    inside = []
    for k, v in zip(yy, lat_):
        if k.startswith('Inside'):
            inside.append(v)
    print(inside)
    

    结果:

    [77.2167, 77.25, 77.2167, 77.2167, 77.2, 77.2167]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多