【问题标题】:can't set the right index in a loop无法在循环中设置正确的索引
【发布时间】:2017-01-01 18:19:20
【问题描述】:
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]) or sec[trips][1]==(all_path[tin-1][n][X]): 问题主要是如何索引 X “X 不是代码的一部分” 我尝试了很多方法来解决它,但它不起作用,我得到的最好的是它改变目的地并一直保持相同的原点,所以成本为 2->3 + 2->4 + 2->5而不是 2->3 + 3->4 + 4->5

【问题讨论】:

  • 我似乎无法计算出我们需要sec 的数据
  • 其实我已经读了3遍了,每次都更糊涂了。至少在我的情况下,如果您将文本块分解并使其更具体,会容易得多。例如,我猜想 sec 有类似 [origin, destination, something, something] 的东西,但随后会上升到 6,但您最多只有 5 命名位置。然后我们有s_dict,它只有5 作为目的地和99 个“站点”。似乎与另一个无关,我无法从代码中得到它,因为那是错误的。
  • 我同意@roganjosh,代码很难阅读。另外,您使用的是什么版本的python?一般来说,请说明一个问题。我们不知道tin 是什么,总的来说一切都不容易理解。
  • 这是一个很长的代码,tin只是一个索引伙伴
  • 这不是一个特别有用的响应。我们可以看到tin 是一个索引,但我们实际上必须可视化您正在尝试做什么。 tin 对我们没有任何意义,因此当您有大量嵌套循环并且没有了解发生了什么的基础时,它只会变得更多 混乱。为了解决这个问题,您的代码陷入了困境,它需要重构,并且只有只有在您给出清晰的问题陈述并清楚地表明您的数据结构的含义时才能完成。

标签: python loops indexing


【解决方案1】:

在 cmets 中来回进行了长时间的来回后,我认为这无法解决您的特定问题。我假设您在到达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')}

【讨论】:

  • 我有点需要索引,因为有一些打印顺序,但你给了我一个想法,虽然目前我想不出创建 cost_dict 的确切方法,但如果它有效,那么我认为会解决的
  • @Enigma 是您问题中main_dict 的准确表示吗?换句话说,有一个索引对应于另一个字典,如{'Origin': '003', 'Destination': '004', 'Cost': '0200.00', 'Time': '11.40'},?在这种情况下,我们可以从中轻松构建成本字典。
  • 在我打开给定文件的代码中,从中获取值并将其应用于 main_dict,这就是我当前的 main_dict 的样子,值可以在文件之间更改,但它会有相同的键
  • 我不太确定,但它没有返回“打印”任何东西
  • @Enigma 什么不是?第一块还是第二块?我的第一个块肯定是在 Python 2 中运行的,我不使用 Python 3,所以我可能错过了一些东西。
【解决方案2】:

如果我正确理解了代码,这里基本上需要的是某种功能。

基本上:

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

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

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

我正在为类似导航应用程序设计寻路算法。我使用以距离为成本的网格地图来执行此操作 顶点之间。这是我的成本函数:

//代码//

有办法优化吗?

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 1970-01-01
    • 2022-01-22
    • 2017-11-03
    • 1970-01-01
    • 2021-05-23
    • 2017-12-20
    • 2015-11-25
    • 1970-01-01
    相关资源
    最近更新 更多