我正在编写一个脚本,目标是检查每个国家(country
(,并根据索引检查supply
列表中是否存在该条目。目标是为每个国家/地区打印出存在和不存在的条目。
国家:
country=['usa', 'poland', 'australia', 'china']
用于检查country
supply
中的每个项目的索引。
# index
water_country=water_<country>_country
gas_state=gas_<country>_state
oil_city=oil_<country>_city
供应:
supply=['water_usa_country', 'gas_usa_state', 'oil_usa_city', 'water_poland_country', 'gas_poland_city', 'gas_australia_state']
对于上述情况,结果将出现在每个国家/地区的列表中:
For country 'usa' all entries exist
For country 'poland' following entries does not exist:
oil_poland_city
For country 'australia' following entries does not exist:
water_australia_country
oil_australia _city
For country 'china' following entries does not exist:
water_china_country
gas_china_state
oil_china_city
这将起作用:
countries = ['usa', 'poland', 'australia', 'china']
search_strings = ['water_{}_country', 'gas_{}_state', 'oil_{}_city']
supply = ['water_usa_country', 'gas_usa_state', 'oil_usa_city', 'water_poland_country', 'gas_poland_city', 'gas_australia_state']
for country in countries:
missing = [search_string.format(country) for search_string in search_strings if search_string.format(country) not in supply]
if missing:
missing_string = 'n'.join(missing)
print(f"For country '{country}' the following entries do not exist:n{missing_string}n")
else:
print(f"For country '{country}' all entries exist.n")
输出:
For country 'usa' all entries exist.
For country 'poland' the following entries do not exist:
gas_poland_state
oil_poland_city
For country 'australia' the following entries do not exist:
water_australia_country
oil_australia_city
For country 'china' the following entries do not exist:
water_china_country
gas_china_state
oil_china_city
您可以简单地迭代每个国家/地区的所有供应并检查满足哪些供应,并将未满足的供应添加到某些列表中,此处的值为 missing_supplies
。
country = ['usa', 'poland', 'australia', 'china']
index = ['water_<country>_country', 'gas_<country>_state', 'oil_<country>_city']
supply = ['water_usa_country', 'gas_usa_state', 'oil_usa_city', 'water_poland_country', 'gas_poland_city', 'gas_australia_state']
missing_supplies = {}
for c in country:
missing_supplies[c] = []
for i in index:
if i.replace('<country>', c) not in supply:
missing_supplies[c].append(i.replace('<country>', c))
for c in country:
if not missing_supplies[c]:
print('For country '{}' all entries exist'.format(c))
else:
print('For country '{}' following entries does not exist:'.format(c))
for v in missing_supplies[c]:
print(v)
print()
输出:
For country 'usa' all entries exist
For country 'poland' following entries does not exist:
gas_poland_state
oil_poland_city
For country 'australia' following entries does not exist:
water_australia_country
oil_australia_city
For country 'china' following entries does not exist:
water_china_country
gas_china_state
oil_china_city