【问题标题】:Repeat a second If condition using or使用或重复第二个 If 条件
【发布时间】:2017-05-11 02:01:13
【问题描述】:
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': '003', 'Destination': '004', 'Cost': '0200.00', 'Time': '11.40'}, 
 4: {'Origin': '002', 'Destination': '004', 'Cost': '0700.00', 'Time': '10.00'}, 
 5: {'Origin': '004', 'Destination': '006', 'Cost': '0550.00', 'Time': '06.75'}, 
 6: {'Origin': '004', 'Destination': '005', 'Cost': '0750.00', 'Time': '10.50'}, 
 7: {'Origin': '005', 'Destination': '006', 'Cost': '0460.00', 'Time': '08.00'}, 
 8: {'Origin': '002', 'Destination': '005', 'Cost': '1500.00', 'Time': '05.75'}}
count=9
first_list=[]                   
second_list=[]
for c in range(1,count):            
    first_list.append(main_dict[c]['Origin'])   #puts all origins in one list
    second_list.append(main_dict[c]['Destination'])#puts all destinations iin one list
locations=[]
locations.extend(first_list)
locations.extend(second_list)
locations=(list(set(locations)))#gets rid of any duplicates
locations.sort()
mat_nxn = [[None for x in range(len(locations))] for y in range(len(locations))] #in this section the main matrix is created 
for i in range(len(locations)):
    mat_nxn[0][i]=locations[i] #fills the first row with the locations
    mat_nxn[i][0]=locations[i] #fills the first column with the locations

for n in range(0,len(locations)-1):
    for i in range(0,len(locations)):
         if str(mat_nxn[0][n])==main_dict[n+1]['Origin'] or str(mat_nxn[i][0])==main_dict[i+1]['Destination'] :
            a=int(mat_nxn[0][n])
            b=int(mat_nxn[n][0])
            mat_nxn[b][a]=main_dict[n+1].values()

所以我的代码应该做的是将字典的信息排列在 NxN 矩阵中,它的工作原理是“Origin”和“Destination”是 martix 的“边界”

然后,如果让我们说我可以按照 SAME 字典中的说明从“Origin”转到“Destination”,它将被添加到矩阵右侧 (X,Y) 下的矩阵中 一个例子是,在第一个字典中,我可以从“Origin 001”转到“Destination 002”,所以我将把字典的值放在矩阵中的 X,Y(001,002) 下 我的问题是在代码的最后一部分,我在两个 for 循环中使用了 if 条件和 or

for n in range(0,len(locations)-1):
   for i in range(0,len(locations)):
     if str(mat_nxn[0][n])==main_dict[n+1]['Origin'] or str(mat_nxn[i][0])==main_dict[i+1]['Destination'] :

现在的问题是,如果我有一个重复的“Origin”在我的情况下是 002,它将不会检查其余的“目的地”,只有第一个,所以我的输出不能完成。我怎样才能让它检查所有这些?我是否以错误的方式使用了or? 希望有任何帮助

【问题讨论】:

  • 输出必须是一个绝对矩阵(列表的列表)?或者它可以是另一个模仿它的结构,比如字典的字典?
  • 不,一个 dicts 的 dict 就可以了,但请记住,如果没有从“Origin”到“Destination”的行程,则 (X,Y) 应该显示 None

标签: python loops dictionary if-statement


【解决方案1】:

@Enigma:这是一个以 dicts 作为输出的解决方案:

import sys

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': '003', 'Destination': '004', 'Cost': '0200.00', 'Time': '11.40'}, 
    4: {'Origin': '002', 'Destination': '004', 'Cost': '0700.00', 'Time': '10.00'}, 
    5: {'Origin': '004', 'Destination': '006', 'Cost': '0550.00', 'Time': '06.75'}, 
    6: {'Origin': '004', 'Destination': '005', 'Cost': '0750.00', 'Time': '10.50'}, 
    7: {'Origin': '005', 'Destination': '006', 'Cost': '0460.00', 'Time': '08.00'}, 
    8: {'Origin': '002', 'Destination': '005', 'Cost': '1500.00', 'Time': '05.75'}
}

locations = {}

origins = set([x['Origin'] for x in main_dict.values()])
destinations = set([x['Destination'] for x in main_dict.values()])

_min = min(origins) if min(origins) < min(destinations) else min(destinations)
_max = max(origins) if max(origins) > max(destinations) else max(destinations)

for origin in origins:
    for destination in destinations:
        if origin not in locations.keys():
            locations[origin] = {}
        if destination not in locations[origin].keys():
            locations[origin][destination] = None

for travel in main_dict.values():
    locations[travel['Origin']][travel['Destination']] = (
        int(travel['Origin']), 
        int(travel['Destination']),
        float(travel['Cost']), 
        float(travel['Time'])
    )

解决方案的表示:

# ||====================================================================================================================================================================================||
# ||          Data          ||          001           ||          002           ||          003           ||          004           ||          005           ||          006           ||
# ||====================================================================================================================================================================================||
# ||          001           ||          None          ||   (1, 2, 100.0, 4.0)   ||          None          ||          None          ||          None          ||          None          ||
# ||          002           ||          None          ||          None          ||   (2, 3, 500.0, 1.5)   ||  (2, 4, 700.0, 10.0)   ||  (2, 5, 1500.0, 5.75)  ||          None          ||
# ||          003           ||          None          ||          None          ||          None          ||  (3, 4, 200.0, 11.4)   ||          None          ||          None          ||
# ||          004           ||          None          ||          None          ||          None          ||          None          ||  (4, 5, 750.0, 10.5)   ||  (4, 6, 550.0, 6.75)   ||
# ||          005           ||          None          ||          None          ||          None          ||          None          ||          None          ||   (5, 6, 460.0, 8.0)   ||
# ||          006           ||          None          ||          None          ||          None          ||          None          ||          None          ||          None          ||
# ||====================================================================================================================================================================================||

重现该输出的讨厌的代码:

def draw():
    _template = '||{: ^24}'
    _range = range(int(_min), int(_max) + 1)
    print("||" + "=" * (26 * (len(_range) + 1) -2) + "||")
    print("||          Data          {}||".format("".join([_template.format(str(x).zfill(3)) for x in _range])))
    print("||" + "=" * (26 * (len(_range) + 1) -2) + "||")
    for origin in _range:
        _origin = str(origin).zfill(3)
        line = _template.format(_origin)    
        for destination in _range:
            #print(_origin, _destination)
            try:
                _destination = str(destination).zfill(3)
                value = locations[_origin][_destination]
                #print(_origin, _destination)
                #print("value",value)
                line += _template.format(str(value))
            except KeyError:
                #print("Error")
                #print(_origin, _destination)
                line += _template.format("None")
        line += '||'
        print(line)
    print("||" + "=" * (26 * (len(_range) + 1) -2) + "||"

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 2018-08-13
    • 2014-01-28
    • 2017-12-26
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多