簡體   English   中英

遍歷字典python

[英]Looping through dictionary python

我在計算路線上的時間時遇到問題。 它以表示路由的字典開頭:

Routing = [('Car1', 'C3', 'C2'),('Car1', 'IT', 'C3'),('Car1', 'C2', 'C4'),('Car1', 'C6', 'IT'),('Car1', 'C4', 'C5'),('Car1', 'C5', 'C6')]

路由中從i [1]到i [2]的每個移動都有自己的時間,並且有一個IT的開始時間:

Time = {('C3', 'C2'): 0,('IT', 'C3'): 14,('C2', 'C4'): 1,('C6', 'IT'): 14,('C4', 'C5'): 0,('C5', 'C6'): 0}
Start_time_IT: 128

如您所見,car1的路由為IT,C3,C2,C4,C5,C6,IT。 IT的起點和終點。 我需要計算每個步驟的到達時間,最后得到一個像這樣的字典:

Arrival_time = {'C3': 142, 'C2': 142, 'C4': 143, 'C5': 143, 'C6':, 143, 'IT': 157} 

例如,C3是根據IT的開始時間(128)和到C3的旅行時間(14)計算得出的,其余部分我得出142,以此類推。

現在,我確實在努力構建Arrival_time。 我已經嘗試過for和while循環,但是我沒有獲得Arrival_time在循環期間更改的錯誤的正確值。

上面是一個示例,實際上路線是多輛汽車和更多停靠點。 有誰知道我如何解決上述情況?

提前Tnx!

使用您提供的信息,這可以幫助您走上正確的道路。 我不知道您在做什么的完整背景,因此可能不是最佳選擇。

def make_route(car, routing):
    # multiple cars in routing so only get connections for the one we want
    connections = [(r[1],r[2]) for r in routing if r[0] == car]

    # get start
    route = [c for c in connections if c[0] == 'IT']

    # join connections
    while route[-1][1] != 'IT':
        route += [c for c in connections if c[0] == route[-1][1]]

    return route


def time_route(route, Time, start_time=0):
    times = []
    for r in route:
        # look up time for the connection and add to running total
        start_time += Time[r]
        # add times to list - dictionaries don't preserve order
        times.append((r[1], start_time))
    return times

r = make_route('Car1', Routing)
Arrival_time = time_route(r, Time, 128)

這應該返回[('C3', 142), ('C2', 142), ('C4', 143), ('C5', 143), ('C6', 143), ('IT', 157)] 這是一個列表,因為字典不會保留順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM