什么更快更有效,多次拆分并将结果存储在变量中:
text = 'Allah is all in all. Allah sees you, and is with you, wherever you are, whatever you do.'
wahed_al_surat = text.split(',')[0]
thalatha_al_surat = text.split(',')[1]
tnan_al_surat = text.split(',')[2]
arbaa_al_surat = text.split(',')[3]
或者将拆分后的列表存储一次,然后按索引访问并将其存储在变量中:
text = 'Allah is all in all. Allah sees you, and is with you, wherever you are, whatever you do.'
splitted = text.split(',') # List accessible by split
wahed_al_surat = splitted[0]
thalatha_al_surat = splitted[1]
tnan_al_surat = splitted[2]
arbaa_al_surat = splitted[3]
如果不是更快,那么两种方式之间的CPU和内存效率如何?你知道吗
对于这类问题,您可以使用timeit模块检查所用的时间,如下所示
只调用
.split()
一次更快,只需创建list对象一次即可启动。Python不会优化或内联额外的方法调用,因为它不能确定每次都会产生相同的结果。你知道吗这里有第三种选择:
此操作只拆分一次,并将4个结果部分中的每个部分指定给4个名称。你知道吗
相关问题 更多 >
编程相关推荐