繁体   English   中英

python 从另一个列表中替换两个列表数据

[英]python replace two list data from another list

在 python 的一个变量中,我得到如下列表:

stop_address_type = ['1','2']

在另一个变量中,我越来越喜欢:

stop_facility_name = ['A','B']  

结果:这就是我真正想要的

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

另一种情况,如:

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

我真正想要的是当我在 stop_address_type 变量中获得 1 值时,我想将 list stop_facility_name 的相同值清空,例如:

这是一个可能的解决方案:

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

这适用于您的stop_address_type列表中的任意数量的“1”。

您可以使用index()方法在 stop_address_type 中获取“1”的索引,然后用空白填充 stop_facility_name:

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

使用stop_address_type = ['1','2']stop_facility_name = ['A','B']您将获得以下 output:

['', 'B']

请注意,这仅在 stop_address_type 中仅出现一次“1”时才有效。


如果您在 stop_address_type 中多次出现“1”,则可以使用列表推导式获取出现“1”的所有索引,并使用简单的 for 循环填充 stop_facility_name 中的相应值:

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)

这将产生以下 output:

['', 'B', '']

您可以通过如下方法传递列表:

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']

这将为您提供所需的 output 无论 1 出现在 adress_type_list 中的哪个位置

如果你想使用stop_facility_name中的第一个值作为stop_address_type的索引,你可以这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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