Python 如何使if条件下的for循环更快

Python 如何使if条件下的for循环更快,python,optimization,networkx,cycle,osmnx,Python,Optimization,Networkx,Cycle,Osmnx,我已经写了一段代码,但它需要大量的时间来运行,我不知道如何使它更快。有人能帮我吗 代码如下: import networkx as nx import matplotlib.pyplot as plt import osmnx as ox import pandas as pd from shapely.wkt import loads as load_wkt import numpy as np import matplotlib.cm as cm ox.config(log_console=

我已经写了一段代码,但它需要大量的时间来运行,我不知道如何使它更快。有人能帮我吗

代码如下:

import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
ox.config(log_console=True, use_cache=True)
import matplotlib as mpl
import random as rd



distrito = ['Lisbon District', 'Setúbal District']
G = ox.graph_from_place(distrito, network_type='all_private')
hospitals = ox.pois_from_place(city, amenities=['hospital'])

coord_1 = (38.74817825481225, -9.160815118526642)  
coord_2 = (38.74110711410615, -9.152159572392323)  
coord_3 = (38.7287248180068, -9.139114834357233) 
target_1 = ox.get_nearest_node(G, coord_1)
target_2 = ox.get_nearest_node(G, coord_2)
target_3 = ox.get_nearest_node(G, coord_3)

nodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)  # Transform nodes and edges into Geodataframes


travel_speed = 20  # km/h
meters_per_minute = travel_speed * 1000 / 60

nodes['shortest_route_length_to_target'] = 0
route_lengths = []
list_nodes = []
i = 0
# print(G.edges(data=True))
for u, v, k, data in G.edges(data=True, keys=True):

    data['time'] = data['length'] / meters_per_minute

for node in G.nodes:
    try:
        route_length_1 = nx.shortest_path_length(G, node, target_1, weight='time')
        route_length_2 = nx.shortest_path_length(G, node, target_3, weight='time')
        if route_length_1 < route_length_2:
            route_lengths.append(route_length_1)
            nodes['shortest_route_length_to_target'][node] = route_length_1
            list_nodes.append(node)
        elif route_length_1 > route_length_2:
            route_lengths.append(route_length_2)
            nodes['shortest_route_length_to_target'][node] = route_length_2
            list_nodes.append(node)

    except nx.exception.NetworkXNoPath:
        continue
将networkx导入为nx
将matplotlib.pyplot作为plt导入
将osmnx作为ox导入
作为pd进口熊猫
从shapely.wkt导入荷载作为荷载
将numpy作为np导入
将matplotlib.cm导入为cm
ox.config(log\u console=True,use\u cache=True)
将matplotlib导入为mpl
将随机导入为rd
distrito=[‘里斯本区’、‘塞图巴尔区’]
G=ox.graph\u from\u place(distrito,network\u type='all\u private')
医院=ox.pois_从_place(城市,便利设施=[“医院])
坐标1=(38.74817825481225,-9.160815118526642)
坐标2=(38.74110711410615,-9.152159572392323)
coord_3=(38.7287248180068,-9.139114834357233)
target_1=ox.get_最近的_节点(G,coord_1)
target_2=ox.get_最近的_节点(G,coord_2)
target_3=ox.get_最近的_节点(G,coord_3)
nodes,edges=ox.graph_to_gdfs(G,nodes=True,edges=True)#将节点和边转换为Geodataframes
行驶速度=20公里/小时
米每分钟=行驶速度*1000/60
节点['shortest_route_length_to_target']=0
路线长度=[]
列表_节点=[]
i=0
#打印(G.边缘(数据=真))
对于u、v、k,G边中的数据(数据=真,关键点=真):
数据['time']=数据['length']/每分钟米
对于G.nodes中的节点:
尝试:
路由长度=nx。最短路径长度(G,节点,目标长度,权重=时间)
路由长度2=nx。最短路径长度(G,节点,目标长度3,权重=时间)
如果路线长度1<路线长度2:
路由长度。追加(路由长度1)
节点['shortest_route_length_to_target'][node]=路由长度_1
列出\u节点。追加(节点)
elif路线长度\u 1>路线长度\u 2:
路由长度。追加(路由长度2)
节点['shortest_route_length_to_target'][node]=路由长度_2
列出\u节点。追加(节点)
除nx.exception.NetworkXNoPath外:
持续
通常直到G.nodes中的
节点:
代码运行速度相当快。这是一个耗时太长的周期


提前感谢您。

您应该分析您的代码,以准确识别哪些是慢的。我很有信心地认为,对于循环,如果条件在该范围内,那么它不是你的(尽管它们可以再优化一点)。看起来几乎所有的时间复杂性都来自于试图在每个for循环运行中求解两条最短路径。这本身就是缓慢的

您可以尝试使用类似的方法计算最短路径,这样会更快


另请注意,自OSMnx v0.13.0起,您无需手动计算。

谢谢您的回答。我正在尝试实施您的建议,我有两个问题:我可以使用igraph的ox.plot\u图吗?另一个问题是:在使用您所说的内容计算times属性之后,为便于我访问而创建的属性的名称是什么?文档中回答了您的两个问题。1) 采用networkx有向图,而不是igraph图,因此2)该函数将“边行程时间(秒)作为新的行程时间边属性添加到图中。”