正常的“def”函数而不是lambd

2024-05-19 09:34:00 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码生成一个网络地图,其中包含按人口(数值来自何处)着色的国家世界.json. 在

import folium

map=folium.Map(location=[30,30],tiles='Stamen Terrain')

map.add_child(folium.GeoJson(data=open('world.json', encoding='utf-8-sig'),
name="Unemployment",
style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))

map.save('file.html')

world.json的链接。在

我想知道是否可以使用由def创建的普通函数而不是lambda函数作为style_function参数的值。我试着为此创建了一个函数:

^{pr2}$

但是,我想不出如何在style_function中使用它。这是可能的还是lambda函数在这里是不可替代的?在


Tags: lambda函数网络jsonmapworldifstyle
2条回答

style_functionlambda可以替换为如下函数:

def style_function(x):
    return {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))

然后您只需将函数名传递给kwarg:

^{pr2}$

如果我理解正确,您需要创建这样的函数(x是geojson):

def my_style_function(x):
    color = ''
    if x['properties']['POP2005'] <= 10e6:
        color = 'green'
    elif x['properties']['POP2005'] < 2*10e6:
        color = 'orange'
    return {'fillColor': color if color else 'red'}

只需将其赋给style_function参数(不带括号):

^{pr2}$

相关问题 更多 >

    热门问题