简体   繁体   中英

Combine two list as key value pair using zip if lists have same values

I have two lists:

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]

I am combining them using the solution given on some posts here by:

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

But my output is {'Inside the area': 77.2167, 'Outside the area': 77.2}

This is happening because the most of the keys are same. I am doing this because I want to map these two list in order to get which values of lat falls inside or outside, and then keep only the ones which fall inside.

您可以压缩它们并在列表推导中添加一个保护:

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

To keep the values that are inside:

Code:

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

Test Code:

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)

Results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM