使用python3查找包含子字符串的列表?

时间:2019-05-25 09:41:48

标签: python python-3.x

查找包含子字符串的列表并使用python3替换子字符串吗?

nested_list=[["abc","def","ghi"],["lkj","poi","mnb"],["ddcode","ddd","zzzv"]]
list=[]
for line in nested_list:
        if line[0] == 'code':  #find a substring
           line[0] == qtycode  # replace 
           list.append(line)

output -->"qtycode","ddd","zzzv" #print that list only

1 个答案:

答案 0 :(得分:0)

尝试一下

>>> nested_list=[["abc","def","ghi"],["lkj","poi","mnb"],["ddcode","ddd","zzzv"]]

>>> new_list = []

>>> for main_index, inner_list in enumerate(nested_list):
         for index, inner_element in enumerate(inner_list):
             if 'code' in inner_element:
                 inner_list[index] = 'qtycode'
                 if (not new_list) or nested_list.index(inner_list) == main_index:
                     new_list = inner_list
                 else:
                     new_list.append(inner_list)

如果存在'qtycode',它将把值更新为'code'


输出:

>>> new_list

['qtycode', 'ddd', 'zzzv']