Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何迭代字符串列表并基于另一个列表修改每个字符串_Python_List - Fatal编程技术网

Python 如何迭代字符串列表并基于另一个列表修改每个字符串

Python 如何迭代字符串列表并基于另一个列表修改每个字符串,python,list,Python,List,大家好,我是编程新手,我有一个问题: 我想修改列表中的字符串,更准确地说,如果子字符串出现在另一个字符串列表中,则删除该子字符串。我尝试过这个解决方案,但不起作用 res=[] a=['ACTGACTG','ACTGAAA','AGGGAGGG','Ernesto','AAGGACTG','X'] b=['ACTG','AA','X'] for x in a: for y in b: if y in x: res.append(x.replace(

大家好,我是编程新手,我有一个问题:

我想修改列表中的字符串,更准确地说,如果子字符串出现在另一个字符串列表中,则删除该子字符串。我尝试过这个解决方案,但不起作用

res=[]
a=['ACTGACTG','ACTGAAA','AGGGAGGG','Ernesto','AAGGACTG','X']
b=['ACTG','AA','X']
for x in a:
    for y in b:
        if y in x:
            res.append(x.replace(y,''))

print(res)
输出:

['', 'AAA', 'ACTGA', 'AAGG', 'GGACTG', '']
现在这方面没有什么问题

  • 我希望“Ernesto”和“Agggagg”出现在结果中,即使b中没有匹配项

  • 第一个输出中的ACTG匹配2次,所以两次都被擦除,我想被擦除一次,所以期望的输出是

  • X被删除了,但我得到了一个空字符串,我只希望没有该条目

  • 所需的输出如下所示


    ['ACTG','A','aggggg','Ernesto','GG']

    您的思路正确,只需添加您希望用新子字符串替换旧子字符串的次数即可

    然后仅在字符串不为空时添加新字符串

    for x in a:
        for y in b:
            x = x.replace(y,'',1)
        if x:
            res.append(x)
    

    您的思路是正确的,只需添加要用新子字符串替换旧子字符串的次数

    然后仅在字符串不为空时添加新字符串

    for x in a:
        for y in b:
            x = x.replace(y,'',1)
        if x:
            res.append(x)
    

    为什么有额外的if语句?这似乎没有必要。除此之外,这只是我的答案。为了避免空字符串,所以如果。如果x中的y是
    if:
    ,因为我睡得不好,为什么要使用额外的if语句?这似乎没有必要。除此之外,这只是我的答案。为了避免空字符串,所以如果。如果y在x中:是因为我睡得不好