为什么我的解决方案打印在一个列表而不是每个项目?

时间:2017-06-26 07:40:32

标签: python list dictionary

我是python的新手,我想模拟一个非常简单的卡车到门的任务。我希望每辆卡车都能安排我可行的门。但是,如果我正在运行下面的模拟,它会给我一个可行门的列表(T1和T2一起可行的门):

[&#39; D1&#39;,&#39; D2&#39;,&#39; D1&#39;,&#39; D2&#39;,&#39; D3&#39;] < / p>

但我想:

T1 = ['D1','D2']

T2 = ['D1','D2',&#39; D3&#39;]

这很重要,因为在此之后,我想根据成本来比较不同的门,并根据每辆车选择最好的车门。

# 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))

2 个答案:

答案 0 :(得分:1)

您需要在内部列表中构建另一个列表,并将其附加到返回的列表中:

# 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 

答案 1 :(得分:1)

我建议您使用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.