正常'def'函数而不是lambda
以下代码会生成一个带有由population填充的国家/地区的Web地图,其值来自world.json。正常'def'函数而不是lambda
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
的值。我尝试了,创造一个功能:
def feature(x):
file = open("world.json", encoding='utf-8-sig')
data = json.load(file)
population = data['features'][x]['properties']['POP2005']
d ={'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}
return d
但是,我想不出如何style_function
使用它。这是可能的还是lambda函数在这里是不可替代的?
的style_function
拉姆达可以用这样的功能所取代:
def style_function(x):
return {'fillColor':'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'}))
然后,你可以通过函数名到kwarg:
folium.GeoJson(
data=...,
name=...,
style_function=style_function
)
'style_function'被用作'GeoJson'的'kwarg' – Wondercricket
Ohhhh,you're对。格式化没有说清楚,谢谢指出。 – thaavik
如果我的理解是正确的,你需要(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
参数(不带括号):
map.add_child(folium.GeoJson(data=open('world.json', encoding='utf-8-sig'),
name="Unemployment",
style_function=my_style_function))
你的意思是'style_function = feature'? – khelwood
或者只是'def style_function'而不是'def feature'? 'style_function'甚至可以在哪里使用? –
另外 - 你真的想每次调用该函数时打开和加载json文件吗?当然 - 你想要做那一部分,然后使用该函数来获得'x'的风格,无论这是... –