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

标签 python loops indexing

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的行程信息进行匹配。在 s_dict[0] 中,客户希望从 Origin '2' 前往 Destination '5',Cost是 0,这意味着价格不重要,Time 也是如此,Stops 是 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=[

[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,那么在 s_dict 中它将采用 2 作为起点,3 作为目的地,取出 cost 变量中的成本值,然后采用 3 作为起点4 作为目标,并将成本与值相加到 cost 变量中。 我的问题出在索引 if sec[trips][0]==(all_path[tin-1][n][X]) 或 sec[trips][1]==(all_path[tin-1] ][n][X]): 问题主要是如何索引 X “X 不是代码的一部分” 我尝试了很多方法来解决它,但它不起作用,我得到的最好的方法是更改​​目的地并始终保持相同的原点,因此成本为 2->3 + 2->4 + 2->5而不是 2->3 + 3->4 + 4->5

最佳答案

经过长时间的评论,我认为这无法回答您的特定问题。我运行的假设是,当您到达 all_path 时,您已经解决了 costs=99 的问题。在这种情况下,我认为您应该将代码重构为如下所示,以摆脱您发现自己陷入的索引 hell 。它绝不是完美的改进,但希望更容易遵循。

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')}

关于python - 无法在循环中设置正确的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41417837/

相关文章:

PHP for 循环 - 如何逃避第一次迭代?

mysql - 当我使用 >= 或 <= 时,我可以在日期字段上放置 mysql 索引吗?

mysql - 对于 m :n-relationship? 我应该在 MySQL 中使用哪些索引

r - 提取向量中的第一个连续序列

python - 与 R 相比,将 mysql 表加载到 python 中需要很长时间

python - pyqt4网页隐藏窗口标题栏

java - 完成链表排序后,我不确定如何跳出循环

c++ - 了解嵌套 for 循环以打印星号模式

python - Django 缓存 : reload browser cache when cache is warmed up

Python 实时鼠标数据与 pyqtgraph