【问题标题】:Cycle through permutations of a list and apply a function to them循环遍历列表的排列并将函数应用于它们
【发布时间】:2015-05-08 12:35:04
【问题描述】:

我正在尝试获取 5 个机场输入的排列列表,以通过距离计算并对每个排列进行计算。

from airports import *
from math import *
import itertools

dicts=TravelLookUp()
dicts.dictAirport('airport.csv')
dicts.dictCurrency('countrycurrency.csv')
dicts.dictCurrencyRates('currencyrates.csv')

#print(airportdict.airportDict)
#airportdict.airportDict[] IS DICTIONARY

#print(test)

#print(AirportDict)
test= dicts.airportDict['DUB'].getLat()
print(test)

airportList=[]
airportHome=[]
airport1=input('Choose the first airport: ').upper()
airport2=input('Choose the second airport: ').upper()
airport3=input('Choose the third airport: ').upper()
airport4=input('Choose the fourth airport: ').upper()
airport5=input('Choose the fifth airport: ').upper()

airportHome=[airport1]
airportList=[airport2,airport3,airport4,airport5]

AirportCombinations = itertools.permutations(airportList,r=4)

def distance(airport1,airport2):
    distacnces=[]
    lat1=dicts.airportDict[airport1].getLat()
    long1=dicts.airportDict[airport1].getLong()
    lat2=dicts.airportDict[airport2].getLat()
    long2=dicts.airportDict[airport2].getLong()
    lat1R= (lat1*pi/180)
    long1R=(long1*pi/180)
    lat2R=(lat2*pi/180)
    long2R=(long2*pi/180)
    distance= acos(sin(lat1R)*sin(lat2R)*cos(long1R-long2R))*6373
    distances.append(distance)
    return distances

for i in AirportCombinations:
    i=list(i)
    route=[airportHome]
    for value in range(len(i)):
            route.append(value)
            totaldistance=0
            for i in range(len(route)-1):
                legcost=distance(route[i],route[i+1])
                totaldistance+=distance
                print(totaldistance)

distance()

路线列表包含排列,我希望它循环遍历每个排列中每个机场对的 distance(airport1,airport2) 函数。

每当我运行它时,它只会计算相同的两个机场之间的距离 24 次,而我想要它做的是计算每个组合的距离。

如何通过distance(airport1,airport2) 函数计算运行所有排列?然后创建一个列表来保存所有这些计算?

【问题讨论】:

  • “获取所有排列”是什么意思?你预计有多少?
  • 那么用户输入了 5 个机场,其中 4 个进入机场列表。然后将其放入 AirportCombinations = itertools.permutations(airportList,r=4) 并应给出以下内容。
  • [('DUB', 'SYD', 'AAL', 'LDN'), ('DUB', 'SYD', 'LDN', 'AAL'), ('DUB', 'AAL', 'SYD', 'LDN'), ('DUB', 'AAL', 'LDN', 'SYD'), ('DUB', 'LDN', 'SYD', 'AAL'), ( 'DUB', 'LDN', 'AAL', 'SYD'), ('SYD', 'DUB', 'AAL', 'LDN'), ('SYD', 'DUB', 'LDN', 'AAL') '), ('SYD', 'AAL', 'DUB', 'LDN'), ('SYD', 'AAL', 'LDN', 'DUB'), ('SYD', 'LDN', 'DUB' ', 'AAL'), ('SYD', 'LDN', 'AAL', 'DUB'), ('AAL', 'DUB', 'SYD', 'LDN'), ('AAL', 'DUB' ', 'LDN', 'SYD'), ('AAL', 'SYD', 'DUB', 'LDN'), ('AAL', 'SYD', 'LDN', 'DUB'), ('AAL ', 'LDN', 'DUB', 'SYD'),]
  • 这些然后通过 AirportCombinations 中的 for i 从小管变为列表: i=list(i) 我想知道如何从 i=list(i) 中获取所有这些排列以运行循环中的def距离函数
  • 4! = 24 ,你得到 24 ,那你需要什么?

标签: python algorithm


【解决方案1】:

我认为从for i in AirportCombinations 开始,您的循环中的事情有些过于复杂了。

我已经简化了该循环(并为清晰起见重命名了您的变量),但保留了您的方法,即为每条路线转换为列表。

你还有一个错字:totaldistance += distance 应该是 totaldistance += legcost,我想。

for sub_route in AirportCombinations:
    route = [airportHome] + list(sub_route)
    totaldistance = 0
    for i in range(len(route)-1):
        legcost = distance(route[i], route[i+1])
        totaldistance += legcost
    
    #I've un-indented this so it prints for each permutation
    print('route ' + str(route) + ' has distance ' + str(totaldistance)) 

    # Add the distance to a list or dictionary here if you want them available later...

另一种方法

您可以完全摆脱内部循环,留给读者看Zen of Python 的哪一部分更重要 - 这更扁平(比嵌套更好),但这是否胜过“可读性计数”...

zip 使用documented behaviour:

当最短的输入迭代用完时,迭代器停止

for sub_route in AirportCombinations:
    route = [airportHome] + list(sub_route)
    totaldistance = sum(distance(a[0], a[1]) for a in zip(route, route[1:]))        
    print('route ' + str(route) + ' has distance ' + str(totaldistance)) 

    # Add the distance to a list or dictionary here if you want them available later...

【讨论】:

    【解决方案2】:

    我认为你的问题在这里:

    for i in AirportCombinations:
        i=list(i)
        route=[airportHome]        
        for value in range(len(i)): <<<
                route.append(value) <<<
                totaldistance=0
                for i in range(len(route)-1):
                    legcost=distance(route[i],route[i+1])
                    totaldistance+=distance
                    print(totaldistance)
    

    当你应该附加 i[value] 时,你正在附加 valueroute

    或者更好的是,直接遍历i

    for i in AirportCombinations:
        i=list(i)
        route=[airportHome]
        for value in i:
                route.append(value)
                totaldistance=0
                for i in range(len(route)-1):
                    legcost=distance(route[i],route[i+1])
                    totaldistance+=distance
                    print(totaldistance)
    

    附: - 在嵌套循环的两个级别中使用 i 只是令人困惑......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-06
      • 2021-01-19
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多