gpt4 book ai didi

python - 最快检查行是否以列表中的值开头?

转载 作者:太空狗 更新时间:2023-10-30 02:58:33 24 4
gpt4 key购买 nike

我有数以千计的值(作为列表,但如果有帮助,可能会转换为字典等)并且想要与具有数百万行的文件进行比较。我想要做的是将文件中的行过滤为仅以列表中的值开头的行

最快的方法是什么?

我的慢代码:

  for line in source_file:
# Go through all IDs
for id in my_ids:
if line.startswith(str(id) + "|"):
#replace comas with semicolons and pipes with comas
target_file.write(line.replace(",",";").replace("|",","))

最佳答案

如果您确定该行以 id +“|”和“|”开头不会出现在 id 中,我想你可以用“|”玩一些把戏。例如:

my_id_strs = map(str, my_ids)
for line in source_file:
first_part = line.split("|")[0]
if first_part in my_id_strs:
target_file.write(line.replace(",",";").replace("|",","))

希望这会有所帮助:)

关于python - 最快检查行是否以列表中的值开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com