You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中根据stop_address_type值清空对应位置的stop_facility_name元素

Solution for Matching List Element Updates in Python

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_type is '1'—if yes, we use an empty string; if not, we keep the original value from stop_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:07:39