在下列拆分情况下,什么更快更有效?

2024-03-29 11:07:31 发布

您现在位置:Python中文网/ 问答频道 /正文

什么更快更有效,多次拆分并将结果存储在变量中:

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和内存效率如何?你知道吗


Tags: andtextinyouiswithallare
2条回答

对于这类问题,您可以使用timeit模块检查所用的时间,如下所示

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import timeit
>>> 
>>> 
>>> code_to_test_1 = """
... 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]
... """
>>> 
>>> 
>>> code_to_test_2 = """
... 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]
... """
>>> 
>>> 
>>> timeit.timeit(code_to_test_1, number=10000000)
14.445806980133057
>>> 
>>> 
>>> timeit.timeit(code_to_test_2, number=10000000)
4.4506120681762695
>>> 

只调用.split()一次更快,只需创建list对象一次即可启动。Python不会优化或内联额外的方法调用,因为它不能确定每次都会产生相同的结果。你知道吗

这里有第三种选择:

wahed_al_surat, thalatha_al_surat, tnan_al_surat, arbaa_al_surat = text.split(',')

此操作只拆分一次,并将4个结果部分中的每个部分指定给4个名称。你知道吗

相关问题 更多 >