[英](Python) which is more efficient to split a string multiple separators? 1) Using multiple replace method then using split 2) using regular Expressions
例子:
(情況1)
#首先使用replace方法將不同類型的分隔符替換為單一類型,然后使用split方法
text = "python is, an easy;language; to, learn."
text_one_delimiter = text.replace("# ", ", ").replace("% ", ", ").replace("; ", ", ").replace("- ", ", ")
print(text_one_delimiter.split(", "))
(案例二)
#使用正則表達式進行拆分使用多個分隔符
import re
text = "python is# an% easy;language- to, learn."
print(re.split('; |, |# |% |- ', text))
timeit模塊對於代碼片段的速度比較很有用。 它可以通過以下方式使用:
import timeit
case1 = '''text = "python is, an easy;language; to, learn."
text_one_delimiter = text.replace("# ", ", ").replace("% ", ", ").replace("; ", ", ").replace("- ", ", ")
text_one_delimiter.split(", ")'''
case2_setup = "import re"
case2 = '''text = "python is# an% easy;language- to, learn."
re.split('; |, |# |% |- ', text)'''
print(timeit.timeit(case1))
print(timeit.timeit(case2,case2_setup))
Output(取決於您的機器):
1.1250261999999793
2.2901268999999616
請注意,我從檢查的代碼中排除了print
並import re
,否則它會在不需要幾次的情況下導入它。 結論是,在這種特殊情況下,具有多個.replace
的方法比re.split
更快。
(在 Python 3.7.3 中測試)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.