如果变量不';在Python中不存在
我有一个如果变量不';在Python中不存在,python,if-statement,try-catch,Python,If Statement,Try Catch,我有一个.yaml文件(params),其中包含一个名称词典 country_names: country_1: Wales country_2: England country_3: Scotland country_4: 正如你所看到的,国家4是空的。这是故意的。出于可伸缩性和用户友好性的考虑,我希望能够使用已知的最大国家/地区名称数(即4)运行脚本,但国家/地区值的数目未知。我也不希望每次有人对yaml进行更改时都必须硬编码脚本 import dicto
.yaml
文件(params
),其中包含一个名称词典
country_names:
country_1: Wales
country_2: England
country_3: Scotland
country_4:
正如你所看到的,国家4是空的。这是故意的。出于可伸缩性和用户友好性的考虑,我希望能够使用已知的最大国家/地区名称数(即4)运行脚本,但国家/地区值的数目未知。我也不希望每次有人对yaml进行更改时都必须硬编码脚本
import dictor
import geopandas as gpd
import pandas as pd
import yaml
country_1 = dictor(params, 'country_names.country_1')
if country_1 is None:
del country_1
else:
country_1_path = path_to_dir + '/' + country_1 + '.geojson'
country_1 = gpd.read_file(country_1)
country_2 = dictor(params, 'country_names.country_2')
if country_2 is None:
del country_2
else:
country_2_path = path_to_dir + '/' + country_2 + '.geojson'
country_2 = gpd.read_file(country_2)
country_3 = dictor(params, 'country_names.country_3')
if country_3 is None:
del country_3
else:
country_3_path = path_to_dir + '/' + country_3 + '.geojson'
country_3 = gpd.read_file(country_3)
country_4 = dictor(params, 'country_names.country_4')
if country_4 is None:
del country_4
else:
country_4_path = path_to_dir + '/' + country_4 + '.geojson'
country_4 = gpd.read_file(country_4)
然后我把上面产生的国家变量连接起来
try:
countries = pd.concat([country_1, country_2, country_3, country_4])
except:
pass
try:
countries = pd.concat([country_1, country_2, country_3])
except:
pass
try:
countries = pd.concat([country_1, country_2])
except:
pass
该脚本完全按照我的要求执行,不会崩溃。然而,正如您所看到的,LOC计数非常高,而且非常混乱。有没有一种更有效或更像蟒蛇的方式来做到这一点,同时保持事物的显性而不是隐性?此外,我也很乐意接受其他建议,例如,如果我错误地使用了except
和pass
*如果有人提出建议,我也很乐意更改问题的标题 您可以这样做,例如:
# The variables that exist, country_2 and country_4 were not initialized
country_1 = 0
country_3 = 1
countries = []
for i in range(1, 5):
if f'country_{i}' in globals():
countries.append(globals()[f'country_{i}'])
print(countries)
[0,1]