Python использует индекс для проверки в списке - PullRequest
0 голосов
/ 02 апреля 2019

Я работаю над сценарием, целью которого является проверка каждой страны (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  

Ответы [ 2 ]

0 голосов
/ 02 апреля 2019

Вы можете просто выполнить итерацию по всем вашим расходным материалам для каждой страны и проверить, какие запасы встречаются, и добавить те, которых нет в каком-либо списке, здесь значения 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
0 голосов
/ 02 апреля 2019

Это будет работать:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...