Python startswith()不会删除所有匹配项

问题描述 投票:0回答:1

[不确定我是否在这里做任何愚蠢的事情,但是我试图删除以00:00:00.开头的列表中的所有项目,但并非所有项目都匹配。

tc = ['00:00:00.360', '00:00:00.920', '00:00:00.060', '00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.140', '00:00:00.280', '00:00:01.200', '00:00:00.400', '00:00:01.220', '00:00:00.380']
for item in tc:
    if item.startswith(str('00:00:00.')):
        tc.remove(item)
print (tc)

结果:

['00:00:00.920', '00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.280', '00:00:01.200', '00:00:01.220']

预期结果:

['00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:01.200', '00:00:01.220']

任何想法这里可能是什么问题?

python
1个回答
5
投票

那是因为您在遍历tc时更改了它。您可以通过简单的列表理解来实现自己的目标:

tc = [item for item in tc if not item.startswith('00:00:00.')]
© www.soinside.com 2019 - 2024. All rights reserved.