我目前正在尝试递归地从python列表中删除某些字符。
我有一份清单:
lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']我想删除“_out”,使列表看起来如下
>>lst1
['ZINC1.pdbqt', 'ZINC2.pdbqt', 'ZINC3.pdbqt']我的当前代码如下:
lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']
for i in lst1:
lst1.strip("_out")但是我得到了一个错误: AttributeError:'list‘object没有属性'strip’。
发布于 2022-07-24 15:23:38
下面的代码实现了您的目标。正如@育空所建议的那样,替换方法对此非常有用。
lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']
lst2 = []
for i in lst1:
lst2.append( i.replace("_out", "") )
print(lst2)发布于 2022-07-24 15:28:31
现在代码的问题是,您试图删除列表,而不是列表中的属性。我鼓励您对for循环进行更多的研究。将来,在问你自己的问题之前,在google上搜索,查看文档,或者寻找其他类似的问题。
字符串的split方法用于从字符串的前后移除字符。在这种情况下,您希望从字符串中间移除特定字符。为此,我们将使用string.replace(characterstoreplace, whattoreplaceitwith)方法。
生成的代码应该如下所示。请尽量为自己理解它,而不是只是复制粘贴它。如果你有什么问题可以问我。
lst1 = ['ZINC1_out.pdbqt', 'ZINC2_out.pdbqt', 'ZINC3_out.pdbqt']
for i in range(len(lst1)): #goes through every attribute in the list, represented by i
lst1[i] = lst1[i].replace("_out", "") #replaces '_out' with nothing and sets the new value发布于 2022-07-24 15:37:56
如果不想理解列表,也可以使用map删除字符串。
list(map(lambda x:x.replace('_out',''),lst1))
Out[136]: ['ZINC1.pdbqt', 'ZINC2.pdbqt', 'ZINC3.pdbqt']要查看性能,让我们尝试使用字符串中的30000组件。
# Appending to list (From @Hanno Reuvers)
%timeit append_list_function()
8.68 ms ± 236 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# List comprehension
%timeit [s.replace('_out', '') for s in newlist]
7.06 ms ± 361 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# Map function
%timeit list(map(lambda x:x.replace('_out',''),newlist))
8.69 ms ± 137 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)https://stackoverflow.com/questions/73099567
复制相似问题