Colman McMahon Colman McMahon - 4 months ago 37
Python Question

Cartopy-Python syntax - multiple objects/countries in one line

I'm following this example, Python Mapping in Matplotlib Cartopy Color One Country. It's fully working with several countries, e.g. USA, France, UK, Japan.

for country in countries:
if country.attributes['adm0_a3'] == 'USA':
ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor='#008744', alpha = 0.5,
label=country.attributes['adm0_a3']),

if country.attributes['adm0_a3'] == 'FRA':
ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor='#008744', alpha = 0.5,
label=country.attributes['adm0_a3']),
+ 'GBR'
+ 'JPN'

else:
ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor=('#c4e6ff'),
label=country.attributes['adm0_a3'])


I'd like to put a list of countries in one line rather than repeating the statements over and over.

I tried:

if country.attributes['adm0_a3'] == ['USA', 'FRA', 'GBR', 'JPN']:


And
any('USA, 'FRA', 'GBR', 'JPN')


And
['USA or 'FRA' or 'GBR' or'JPN']


And a dict:

myDict = {'USA', 'FRA', 'GBR', 'JPN'}
if country.attributes['adm0_a3'] == myDict:


Obviously, I'm not getting the logic quite right.

Answer

You should use the in keyword, something like this:

for country in countries:
    if country.attributes['adm0_a3'] in ['USA', 'FRA', 'GBR', 'JPN']:
        ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                          facecolor=(0, 0, 1),
                          label=country.attributes['adm0_a3'])
    else:
        ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                          facecolor=('#c4e6ff'),
                          label=country.attributes['adm0_a3'])

Is that what you were looking for?

Comments