簡體   English   中英

為什么我的解決方案打印在一個列表中而不是每個項目中?

[英]Why is my solution printed out in one list and not per item?

我是python的新手,我想模擬一個非常簡單的卡車到門分配。 我想為每輛卡車“ t”安排可行的門“ d”。 但是,如果我在下面運行模擬,它將為我提供總的可行門列表(因此T1和T2的可行門合計):

['D1','D2','D1','D2','D3']

但我想擁有:

T1 = ['D1','D2']

T2 = ['D1','D2','D3']

這很重要,因為在此之后,我要根據成本比較不同的門,然后根據該門為每輛卡車“ t”選擇最佳的門。

# define dataset trucks and doors
trucks = ['T1', 'T2']
doors = ['D1', 'D2', 'D3', 'D4']

# define arrival time trucks 
arr_time = {
    'T1': 08.00,
    'T2': 09.00,
}

# define when door 'd' is free
free_time_door = {
    'D1': 07.00,
    'D2': 08.00,
    'D3': 09.00,
    'D4': 10.00
}

# define when door 'd' is feasible for truck 't' to assign to
def feasible_doors(trucks):
    feasible = []
    for t in trucks:
        for d in doors:
            if arr_time[t] >= free_time_door[d]:
                feasible.append(d)
    return feasible 

print (feasible_doors(trucks))

您需要在內部列表中構建另一個列表,並將其附加到返回的列表中:

# define when door 'd' is feasible for truck 't' to assign to
def feasible_doors(trucks):
    feasible = []
    for t in trucks:
        feasible_truck = []
        for d in doors:
            if arr_time[t] >= free_time_door[d]:
                feasible_truck.append(d)
        feasible.append(feasible_truck)
    return feasible 

我建議您使用defaultdict ,以便在一個變量中獲得每輛卡車的可行門。

from collections import defaultdict

# define when door 'd' is feasible for truck 't' to assign to
def feasible_doors(trucks):
    feasible = defaultdict(list)
    for t in trucks:
        for d in doors:
            if arr_time[t] >= free_time_door[d]:
                feasible[t].append(d)
    return feasible 

print (feasible_doors(trucks))

將輸出:

{'T2': ['D1', 'D2', 'D3'], 'T1': ['D1', 'D2']}

編輯 :有關defaultdict更多信息

要選擇卡車的門,只需要將密鑰作為dict的參數傳遞即可:

feasible = feasible_doors(trucks)

print feasible['T1']
# ['D1', 'D2']

或者使用items()在其上循環:

for key, values in feasible.items():
  if key == 'T1':
    doors = ', '.join(values)
    print('The truck: {truck} have {doors} doors free.'.format(truck=key, doors=doors))
# The truck: T1 have D1, D2 doors free.

暫無
暫無

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

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