简体   繁体   中英

python replace two list data from another list

In python in one variable i am getting list like:

stop_address_type = ['1','2']

and in another variable i am getting like:

stop_facility_name = ['A','B']  

Result: this is what i actually want

stop_address_type = ['1','2']
stop_facility_name = ['','B']

another situation like:

stop_address_type = ['2','1']
stop_facility_name = ['A','']

what i actually want is when i ll get the 1 value in stop_address_type variable i want to blank the same value of list stop_facility_name like:

Here is a possible solution:

stop_facility_name = [n if t != '1' else ''
                      for n, t in zip(stop_facility_name, stop_address_type)]

This works with any number of '1's in your stop_address_type list.

You could get the index of '1' in stop_address_type using the index() method and then fill stop_facility_name with a blank:

i = stop_address_type.index('1')
stop_facility_name[i] = ''
print(stop_facility_name)

With stop_address_type = ['1','2'] and stop_facility_name = ['A','B'] you will get the following output:

['', 'B']

Please note that this will only work if there is only one occurrence of '1' in stop_address_type.


If you have more than one occurrence of '1' in stop_address_type, you could use list comprehension to get all the indices of the '1' occurrence and fill the corresponding values in stop_facility_name with a simple for loop:

stop_address_type = ['1','2','1']
stop_facility_name = ['A','B', 'C']
indices = [i for i in range(len(stop_address_type)) if stop_address_type[i] == '1']
for i in indices:
    stop_facility_name[i] = ''
print(stop_facility_name)

This will produce the following output:

['', 'B', '']

You could pass the lists through a method like this:

stop_address_type = ['1', '2']
stop_facility_name = ['A', 'B']

def check_facility_name(address_typ_list, facility_name_list):
    for i, obj in enumerate(address_typ_list):
        if obj == '1':
            facility_name_list[i] = ""

print(stop_facility_name)
# ['A', 'B']

check_facility_name(stop_address_type, stop_facility_name)

print(stop_facility_name)
# ['', 'B']

This will give you the desired output no matter where the 1 occurs in the adress_type_list

If you want to use the first value in stop_address_type as an index into stop_facility_name , you can do it like this:

stop_facility_name[int(stop_address_type[0])] = ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM