无法在循环中设置正确的索引

2024-04-27 12:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

for rout in range(1,6):
    print  'From: '+str(int(s_dict[rout]['Origin']))+','+' to: '+str(int((s_dict[rout]['Destination'])))+','+' Stops: '+(s_dict[rout]['Stops'])+','+' Cost: '+(s_dict[rout]['Cost'])+','+' Time: '+(s_dict[rout]['Time']) 
    print  'All routes:'
    for n in range(len(all_path[rout-1])):
        all_routs=''
        for s in range(len(all_path[rout-1][n])):
            all_routs+=   str(all_path[rout-1][n][s])
            stops=str(len(all_routs)-2)
            cost=0
        for trips in range(len(sec)):
            if sec[trips][X]==(all_path[rout-1][n][0]) or sec[trips][X]==(all_path[rout-1][n][1]):
            cost+=sec[trips][3]    
        print  '->'.join(all_routs)+', Stops: '+stops+', Cost: '+str(cost)

X索引不是代码的一部分,因为它是导致问题的原因,我找不到一个正确的方法来索引它

代码的目的是从s_dict获取“请求”,并将其与main_dict的trip信息相匹配。在s_dict[0]中,客户希望从Origin'2'到Destination'5',Cost是0,这意味着价格不重要,同样的TimeStops是99,这也意味着数量不重要。 现在我应该找到从“2”到“5”的所有可用路径,并返回每个路径花费/消耗的时间

s_dict={

1: {'Origin': '002', 'Destination': '005', 'Cost': '0000.00', 'Stops': '99', 'Time': '00.00'},

2: {'Origin': '002', 'Destination': '005', 'Cost': '0000.00', 'Stops': '11', 'Time': '00.00'},

3: {'Origin': '002', 'Destination': '005', 'Cost': '1450.11', 'Stops': '99', 'Time': '00.00'},

4: {'Origin': '004', 'Destination': '005', 'Cost': '1550.11', 'Stops': '99', 'Time': '22.22'},

5: {'Origin': '001', 'Destination': '005', 'Cost': '0000.00', 'Stops': '99', 'Time': '11.00'}}

main_dict=

{1: {'Origin': '001', 'Destination': '002', 'Cost': '0100.00', 'Time': '04.00'},

2: {'Origin': '002', 'Destination': '003', 'Cost': '0500.00', 'Time': '01.50'},

3: {'Origin': '002', 'Destination': '004', 'Cost': '0700.00', 'Time': '10.00'},

4: {'Origin': '002', 'Destination': '005', 'Cost': '1500.00', 'Time': '05.75'},

5: {'Origin': '003', 'Destination': '004', 'Cost': '0200.00', 'Time': '11.40'},

6: {'Origin': '004', 'Destination': '005', 'Cost': '0750.00', 'Time': '10.50'},

7: {'Origin': '004', 'Destination': '006', 'Cost': '0550.00', 'Time': '06.75'}}

我从main_dict中取出了这些信息,因为这样对我来说更容易处理,并且sec

sec=[

[1, 2, 4.0, 100.0],

[2, 3, 1.5, 500.0],

[2, 4, 10.0, 700.0],

[2, 5, 5.75, 1500.0],

[3, 4, 11.4, 200.0],

[4, 5, 10.5, 750.0],

[4, 6, 6.75, 550.0]]

all_path=[

[[2, 3, 4, 5], [2, 4, 5], [2, 5]],

[[4, 5]],

[[1, 2, 3, 4, 5], [1, 2, 4, 5], [1, 2, 5]]]

all_path来自s_dict 在前三种情况下需要2个特定值它是2->;5这意味着我要从起点2到目的地5,我应该显示所有可用的路线,这意味着2->;3->;4->;5,2->;4->;5,2->;5 这就是路,现在我想知道每次旅行的费用。 换言之,如果我们取2->;4->;5,那么在su dict中,它将取2作为起点,3作为终点,计算出cost变量中的成本值,然后取3作为起点,4作为终点,并将成本值和cost变量相加。 我的问题是索引if sec[trips][0]==(all_path[tin-1][n][X]) or sec[trips][1]==(all_path[tin-1][n][X]):问题主要是如何索引X“X不是代码的一部分” 我尝试了很多方法来解决这个问题,但都不管用,我得到的最好的办法是改变目的地并始终保持相同的原点,所以成本是2->;3+2->;4+2->;5,而不是2->;3+3->;4+4->;5


Tags: pathgtfortimesecoriginalldestination
2条回答

在评论中反复讨论了很长时间后,我认为这不能回答你的具体的问题。我的假设是,到all_path时,您已经解决了costs=99的问题。在这种情况下,我认为您应该将代码重构为如下内容,以摆脱您所处的索引地狱。它绝不是完美的精炼,但希望更容易遵循。你知道吗

import random
import itertools 

###### Generate some fake data for our dict ######

# First get all of our location pairings as tuples
loc_pairs = list(itertools.product(range(1, 6), range(1, 6)))

# Build cost dictionary. Tuple key is (from-location, to-location)
cost_dict = {}
for loc_pair in loc_pairs:
    cost_dict[loc_pair] = {'cost': random.randint(0, 50), 
                           'time': random.randint(0, 50)}

##### Now your data for paths ######
all_path=[[[2, 3, 4, 5], [2, 4, 5], [2, 5]], [[4, 5]], [[1, 2, 3, 4, 5], 
            [1, 2, 4, 5], [1, 2, 5]]]

### Build the printout
for start_location in all_path:
    for route in start_location:
        locations_visited = ' -> '.join(str(item) for item in route)
        costs = 0
        times = 0
        try:
            for x in range(len(route)-1):
                costs += cost_dict[(route[x], route[x+1])]['cost']
                times += cost_dict[(route[x], route[x+1])]['time']
            print("The route: {}".format(locations_visited))
            print("costs:     {}".format(costs))
            print("took:      {}".format(times))
        except:
            pass

假设您的main_dict的数据结构是准确的,您可以使用以下内容构建一个真正的成本字典:

real_costs = {1: {'Origin': '001', 'Destination': '002', 'Cost': '0100.00', 'Time': '04.00'},
2: {'Origin': '002', 'Destination': '003', 'Cost': '0500.00', 'Time': '01.50'},
3: {'Origin': '002', 'Destination': '004', 'Cost': '0700.00', 'Time': '10.00'},
4: {'Origin': '002', 'Destination': '005', 'Cost': '1500.00', 'Time': '05.75'},
5: {'Origin': '003', 'Destination': '004', 'Cost': '0200.00', 'Time': '11.40'},
6: {'Origin': '004', 'Destination': '005', 'Cost': '0750.00', 'Time': '10.50'},
7: {'Origin': '004', 'Destination': '006', 'Cost': '0550.00', 'Time': '06.75'}}

real_cost_dict = {}

for key, value in real_costs.items():
    pairing = (value.get('Origin'), value.get('Destination'))
    real_cost_dict[pairing] = {'cost': value.get('Cost'), 
                               'time': value.get('Time')}

如果我正确理解了代码,这里基本上需要的是某种函数。你知道吗

基本上:

def path_finding_algorithm('[INPUT]'):
    //loads of processing here
    //
    // '[PROCESS]'
    //
    return '[OUTPUT]'

您只向我们提供了['OUTPUT']['PROCESS']的缩短版本。但是我们必须知道['INPUT']是什么,以及['PROCESS']试图做什么。
否则,没有足够的信息来回答您的问题。你知道吗

一个好的开始是陈述一种情况:

I am designing a path finding-algorithm for something like a navigation app. I do this using a grid map with costs as distance between vertices. This is my cost function:

//CODE//

Is there a way to optimise it?

相关问题 更多 >