简体   繁体   English

Python:如何迭代3个列表

[英]Python: How to iterate 3 lists

Doing a course in my own time called GeoPython 2018 and am heavily stuck on Lesson 3, Exercise 3. 在我自己的时间里做一个名为GeoPython 2018的课程,并且沉迷于第3课练习3。

The content so far has been conditional statements, loops and lists (no dictionaries). 到目前为止的内容是条件语句,循环和列表(无字典)。

THE PROBLEM : 问题

We are asked to take a list of weather station names, a list of latitudes and a list of longitudes and divide them up into 4 regions (NE, NW, SE, SW) defined by the cutoffs. 我们被要求获取一个气象站名称列表,一个纬度列表和一个经度列表,并将它们划分为四个由截止点定义的区域(NE,NW,SE,SW)。

# Station names
stations = ['Hanko Russarö', 'Heinola Asemantaus', 'Helsinki Kaisaniemi', 
        'Helsinki Malmi airfield', 'Hyvinkää Hyvinkäänkylä', 'Joutsa Savenaho', 
        'Juuka Niemelä', 'Jyväskylä airport', 'Kaarina Yltöinen', 'Kauhava airfield', 
        'Kemi Kemi-Tornio airport', 'Kotka Rankki', 'Kouvola Anjala', 
        'Kouvola Utti airport', 'Kuopio Maaninka', 'Kuusamo airport', 
        'Lieksa Lampela', 'Mustasaari Valassaaret', 'Parainen Utö', 'Pori airport', 
        'Rovaniemi Apukka', 'Salo Kärkkä', 'Savonlinna Punkaharju Laukansaari', 
        'Seinäjoki Pelmaa', 'Siikajoki Ruukki', 'Siilinjärvi Kuopio airport', 
        'Tohmajärvi Kemie', 'Utsjoki Nuorgam', 'Vaala Pelso', 'Vaasa airport', 
        'Vesanto Sonkari', 'Vieremä Kaarakkala', 'Vihti Maasoja', 'Ylitornio Meltosjärvi']

# Latitude coordinates of Weather stations  
lats = [59.77, 61.2, 60.18, 60.25, 60.6, 61.88, 63.23, 62.4,
   60.39, 63.12, 65.78, 60.38, 60.7, 60.9, 63.14, 65.99,
   63.32, 63.44, 59.78, 61.47, 66.58, 60.37, 61.8, 62.94,
   64.68, 63.01, 62.24, 70.08, 64.5, 63.06, 62.92, 63.84,
   60.42, 66.53]

 # Longitude coordinates of Weather stations 
lons = [22.95, 26.05, 24.94, 25.05, 24.8, 26.09, 29.23, 25.67, 
   22.55, 23.04, 24.58, 26.96, 26.81, 26.95, 27.31, 29.23, 
   30.05, 21.07, 21.37, 21.79, 26.01, 23.11, 29.32, 22.49, 
   25.09, 27.8, 30.35, 27.9, 26.42, 21.75, 26.42, 27.22, 
   24.4, 24.65]

# Cutoff values that correspond to the centroid of Finnish mainland
# North - South
north_south_cutoff = 64.5

# East-West
east_west_cutoff = 26.3

The end result is to populate the following lists with station names that are correctly assigned: 最终结果是使用正确分配的站名填充以下列表:

north_west = []
north_east = []
south_west = []
south_east = []

I have been at this for maybe 3-4 hours with no progress, have tried to use dictionaries 我在这里待了3-4个小时,没有任何进展,尝试过使用字典

data = [{'station':stat, 'latitude': lat, 'longitude': lon}
    for stat, lat, lon in zip(stations, lats, lons)
   ]

But am not getting any further, additionally I get the impression the course organisers want people to focus on iterations and conditionals. 但是没有任何进一步的了解,此外,我给人的印象是课程组织者希望人们专注于迭代和条件。

Any advice or nudge in a direction would be helpful. 任何建议或在方向上的推动都会有所帮助。 This is also my first post so apologise if there is a lack of clarity. 这也是我的第一篇文章,如果缺乏明确性,请您深表歉意。

这是其中之一(如果西方的经度低,则道歉,然后将>切换为<):

north_west = [ a["station"] for a in data if a["latitude"] > north_south_cutoff and a["longitude"] > east_west_cutoff ]

The course you are following is quite generous with hints , and they include instructions on what you should accomplish with this exercise : 您遵循的课程非常丰富,带有提示 ,其中包括有关您应完成此练习的说明

  1. Create four lists for geographical zones in Finland (ie nort_west , north_east , south_west , south_east ) 创建于芬兰的地理区域四个列表(即nort_westnorth_eastsouth_westsouth_east
  2. Iterate over values and determine to which geographical zone the station belongs 遍历值并确定站点属于哪个地理区域
    1. Hint: You should create a loop that iterates N -number of times. 提示:您应该创建一个循环N次的循环。 Create a variable N that should contain the number of stations we have here. 创建一个变量N ,其中应包含我们此处拥有的站点数。
    2. You should use a conditional statement to find out if the latitude coordinate of a station is either North or South of the center point of Finland ( 26.3, 64.5 ) AND if the longitude location is West or East from that center point. 您应该使用条件语句来确定站点的纬度坐标是芬兰中心点的北或南( 26.3, 64.5并且经度位置是该中心点的西还是东。
    3. You should insert the name of the station into the correct geographical zone list (step 1) 您应该将电台名称插入正确的地理区域列表中(步骤1)
  3. Print out the names of stations at each geographical zone 打印每个地理区域的电台名称

You covered point 1, and found a more efficient method to accomplish point 2.1 (looping over the 3 lists). 您介绍了第1点,并发现了一种更有效的方法来完成第2.1点(遍历3个列表)。 To accomplish point 2.2, look at those hints I linked to at the start, specifically the Nested if statements section. 为了完成第2.2点,请看一开始我链接到的那些提示,特别是Nested if语句部分。 If that doesn't quite help you solve this, you want to re-reach the conditional statements chapter . 如果那不能完全帮助您解决此问题,请重新阅读条件语句一章

The basic structure of what they you want to do is this: 他们想要做什么的基本结构是这样的:

north_west = []
north_east = []
south_west = []
south_east = []

N = len(stations)

for i in range(N):
    station = stations[i]
    lat = lats[i]
    lon = lons[i]

    if <<test to see if lon is east of 26.3>>:
        if <<test to see if lat is north of 64.5>>:
            # add station to the north_east list
        else:  # south or at 64.5
            # add station to the south_east list
    else:  # west or at 26.3
        if <<test to see if lat is north of 64.5>>:
            # add station to the north_west list
        else:  # south or at 64.5
            # add station to the south_west list

then print the names in each of the four lists. 然后在四个列表中的每个列表中打印名称。 Note that I left out the actual conditions for you to fill in here. 请注意,我省略了实际条件供您在此处填写。

There are more efficient and 'clever' ways of achieving the above, you found one, were for i in range(N): and 3 separate assignments can be replaced by for station, lat, lon in zip(....): . 您发现有一种更有效的“聪明”方法,可以实现for i in range(N):for i in range(N): :,并且可以用for station, lat, lon in zip(....):替换3个单独的分配for station, lat, lon in zip(....): However, I'd stick to the above pattern for now. 但是,我现在将坚持上述模式。 I've included a different approach below, hidden as a spoiler block so as not to distract you too much: 我在下面提供了另一种方法,隐藏为扰流板,以免分散您的注意力:

If you wanted to be super-clever, you could create a mapping from (boolean, boolean) tuples to those 4 lists to select each list: regions = { # north?, east? 如果您想成为超级聪明人,则可以创建一个从(boolean, boolean)元组到这4个列表的映射(boolean, boolean)以选择每个列表:region = {##north ?, east? (False, False): south_west, (False, True ): south_east, (True, False): north_west, (True, True ): north_east, } for station, lon, lat in zip(stations, lons, lats): regions[lat > 64.5, lon > 26.3].append(station) but that's definitely beyond the course requirements. (False,False):south_west,(False,True):south_east,(True,False):north_west,(True,True):north_east,} for邮编,lon,lat in zip(stations,lons,lats):地区[lat> 64.5,lon> 26.3] .append(station),但这绝对超出了课程要求。 :-) :-)

The advice is to use enumerate build-in function to get an index and a value (station name) from the first list. 建议使用枚举内置函数从第一个列表中获取索引和值(站名)。 Then you use the index to get two more values (latitude and longitude) and check these value to determine what region they belong to. 然后,您可以使用索引获取另外两个值(纬度和经度),然后检查这些值以确定它们属于哪个区域。 Then add this name to result list station_list[quatrant].append(name) 然后将此名称添加到结果列表station_list [quatrant] .append(name)

Here is the solution: 解决方法如下:

# Cutoff values that correspond to the centroid of Finnish mainland
# North - South
north_south_cutoff = 64.5

# East-West
east_west_cutoff = 26.3

# Station names
stations = ['Hanko Russarö', 'Heinola Asemantaus', 'Helsinki Kaisaniemi',
        'Helsinki Malmi airfield', 'Hyvinkää Hyvinkäänkylä', 'Joutsa Savenaho',
        'Juuka Niemelä', 'Jyväskylä airport', 'Kaarina Yltöinen', 'Kauhava airfield',
        'Kemi Kemi-Tornio airport', 'Kotka Rankki', 'Kouvola Anjala',
        'Kouvola Utti airport', 'Kuopio Maaninka', 'Kuusamo airport',
        'Lieksa Lampela', 'Mustasaari Valassaaret', 'Parainen Utö', 'Pori airport',
        'Rovaniemi Apukka', 'Salo Kärkkä', 'Savonlinna Punkaharju Laukansaari',
        'Seinäjoki Pelmaa', 'Siikajoki Ruukki', 'Siilinjärvi Kuopio airport',
        'Tohmajärvi Kemie', 'Utsjoki Nuorgam', 'Vaala Pelso', 'Vaasa airport',
        'Vesanto Sonkari', 'Vieremä Kaarakkala', 'Vihti Maasoja', 'Ylitornio Meltosjärvi']

# Latitude coordinates of Weather stations
lats = [59.77, 61.2, 60.18, 60.25, 60.6, 61.88, 63.23, 62.4,
   60.39, 63.12, 65.78, 60.38, 60.7, 60.9, 63.14, 65.99,
   63.32, 63.44, 59.78, 61.47, 66.58, 60.37, 61.8, 62.94,
   64.68, 63.01, 62.24, 70.08, 64.5, 63.06, 62.92, 63.84,
   60.42, 66.53]

 # Longitude coordinates of Weather stations
lons = [22.95, 26.05, 24.94, 25.05, 24.8, 26.09, 29.23, 25.67,
   22.55, 23.04, 24.58, 26.96, 26.81, 26.95, 27.31, 29.23,
   30.05, 21.07, 21.37, 21.79, 26.01, 23.11, 29.32, 22.49,
   25.09, 27.8, 30.35, 27.9, 26.42, 21.75, 26.42, 27.22,
   24.4, 24.65]

region_name = ['North-West', 'North East', 'South West', 'South East']

NW = 0
NE = 1
SW = 2
SE = 3

def divide_station(stations, lats, lons):
    station_list = [[] for _ in range(SE+1)]
    for index, name in enumerate(stations):
        if lats[index] > north_south_cutoff:
            quatrant = NE if lons[index] > east_west_cutoff else NW
        else:
            quatrant = SE if lons[index] > east_west_cutoff else SW
        station_list[quatrant].append(name)
    return station_list

north_west, north_east, south_west, south_east = divide_station(stations, lats, lons)

station_list = [north_west, north_east, south_west, south_east]

for index, region in enumerate(station_list):
    print('\nRegion:', region_name[index])
    for number, name in enumerate(region):
        print('%2d. %s' % (number+1, name))

Output: 输出:

Region: North-West
 1. Kemi Kemi-Tornio airport
 2. Rovaniemi Apukka
 3. Siikajoki Ruukki
 4. Ylitornio Meltosjärvi

Region: North East
 1. Kuusamo airport
 2. Utsjoki Nuorgam

Region: South West
 1. Hanko Russarö
 2. Heinola Asemantaus
 3. Helsinki Kaisaniemi
 4. Helsinki Malmi airfield
 5. Hyvinkää Hyvinkäänkylä
 6. Joutsa Savenaho
 7. Jyväskylä airport
 8. Kaarina Yltöinen
 9. Kauhava airfield
10. Mustasaari Valassaaret
11. Parainen Utö
12. Pori airport
13. Salo Kärkkä
14. Seinäjoki Pelmaa
15. Vaasa airport
16. Vihti Maasoja

Region: South East
 1. Juuka Niemelä
 2. Kotka Rankki
 3. Kouvola Anjala
 4. Kouvola Utti airport
 5. Kuopio Maaninka
 6. Lieksa Lampela
 7. Savonlinna Punkaharju Laukansaari
 8. Siilinjärvi Kuopio airport
 9. Tohmajärvi Kemie
10. Vaala Pelso
11. Vesanto Sonkari
12. Vieremä Kaarakkala

You could use a while loop to iterate through all these latitude and longitude values and then checking the conditions for 您可以使用while循环迭代所有这些经度和纬度值,然后检查条件

NW (lat>NWcutoff&lon<EWcutoff)

NE (lat>NWcutoff&lon>EWcutoff)

SW (lat<NWcutoff&lon<EWcutoff)

SE (lat<NWcutoff&lon>EWcutoff)

And then appending the station name to the respective list. 然后将站点名称附加到相应的列表中。

So the complete, simple and clean code would look like : 因此,完整,简单和干净的代码如下所示:

    stations = ['Hanko Russarö', 'Heinola Asemantaus', 'Helsinki Kaisaniemi', 'Helsinki Malmi airfield', 'Hyvinkää Hyvinkäänkylä', 'Joutsa Savenaho', 'Juuka Niemelä', 'Jyväskylä airport', 'Kaarina Yltöinen', 'Kauhava airfield', 'Kemi Kemi-Tornio airport', 'Kotka Rankki', 'Kouvola Anjala', 'Kouvola Utti airport', 'Kuopio Maaninka', 'Kuusamo airport', 'Lieksa Lampela', 'Mustasaari Valassaaret', 'Parainen Utö', 'Pori airport', 'Rovaniemi Apukka', 'Salo Kärkkä', 'Savonlinna Punkaharju Laukansaari', 'Seinäjoki Pelmaa', 'Siikajoki Ruukki', 'Siilinjärvi Kuopio airport', 'Tohmajärvi Kemie', 'Utsjoki Nuorgam', 'Vaala Pelso', 'Vaasa airport', 'Vesanto Sonkari', 'Vieremä Kaarakkala', 'Vihti Maasoja', 'Ylitornio Meltosjärvi']

    lats = [59.77, 61.2, 60.18, 60.25, 60.6, 61.88, 63.23, 62.4, 60.39, 63.12, 65.78, 60.38, 60.7, 60.9, 63.14, 65.99, 63.32, 63.44, 59.78, 61.47, 66.58, 60.37, 61.8, 62.94, 64.68, 63.01, 62.24, 70.08, 64.5, 63.06, 62.92, 63.84, 60.42, 66.53]

    lons = [22.95, 26.05, 24.94, 25.05, 24.8, 26.09, 29.23, 25.67, 22.55, 23.04, 24.58, 26.96, 26.81, 26.95, 27.31, 29.23, 30.05, 21.07, 21.37, 21.79, 26.01, 23.11, 29.32, 22.49, 25.09, 27.8, 30.35, 27.9, 26.42, 21.75, 26.42, 27.22, 24.4, 24.65]
    i=0
    north_south_cutoff = 64.5
    east_west_cutoff = 26.3
    north_east=[]
    north_west=[]
    south_east=[]
    south_west=[]
    for i in range(0,len(stations)):
            if lats[i]>north_south_cutoff and lons[i]>east_west_cutoff:
                      north_east.append(str(stations[i]))
            elif lats[i]<north_south_cutoff and lons[i]>east_west_cutoff:
                      south_east.append(str(stations[i]))
            elif lats[i]>north_south_cutoff and lons[i]<east_west_cutoff:
                      north_west.append(str(stations[i]))
            elif lats[i]<north_south_cutoff and lons[i]<east_west_cutoff:
                      south_west.append(str(stations[i]))
    print(north_east)
    print(north_west)
    print(south_east)
    print(south_west)

This will put all stations in respective lists after comparing longitudes and latitudes on basis of off-set. 在根据偏移量比较经度和纬度之后,这会将所有电台置于相应的列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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