Python中根据stop_address_type值清空对应位置的stop_facility_name元素
Got it, let's break down how to solve this problem exactly as you described. The key rule we need to enforce is: any position in stop_facility_name where the corresponding position in stop_address_type is '1' must be set to an empty string, while all other elements stay as they are.
Method 1: Pythonic List Comprehension
This is the cleanest way to handle this in Python—we can pair up elements from both lists using zip() and build the updated stop_facility_name in one line:
# Example 1: Original input stop_address_type = ['1', '2'] stop_facility_name = ['A', 'B'] # Apply the rule stop_facility_name = ['' if addr_type == '1' else original for addr_type, original in zip(stop_address_type, stop_facility_name)] print(stop_facility_name) # Output: ['', 'B']
# Example 2: Reverse order input stop_address_type = ['2', '1'] stop_facility_name = ['A', ''] # Apply the same rule stop_facility_name = ['' if addr_type == '1' else original for addr_type, original in zip(stop_address_type, stop_facility_name)] print(stop_facility_name) # Output: ['A', ''] (already empty, so no change needed)
How this works:
zip(stop_address_type, stop_facility_name)pairs each element from the two lists by their position (e.g., first element of the first list with first element of the second).- For each pair, we check if the
addr_typeis '1'—if yes, we use an empty string; if not, we keep the original value fromstop_facility_name.
Method 2: In-Place Modification with a Loop
If you prefer to modify the original stop_facility_name list directly instead of creating a new one, you can use an index-based loop:
stop_address_type = ['2', '1'] stop_facility_name = ['A', ''] for i in range(len(stop_address_type)): if stop_address_type[i] == '1': stop_facility_name[i] = '' print(stop_facility_name) # Output: ['A', '']
This iterates over each index position, checks the value in stop_address_type, and updates stop_facility_name in place when the condition is met.
Both methods will handle any order of elements in stop_address_type and correctly update the corresponding positions in stop_facility_name as required.
内容的提问来源于stack exchange,提问作者Shruti

