在python中将字符串转换为数组的最快方法是什么? [英] What is the fastest way to convert string to array in python?
问题描述
这是我从文本文件中读取的一行:
This is a line I read from a text file:
[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]
我使用readline()以字符串形式读取它.现在,将其转换回数组的最快方法是什么?
I used readline() to read it in as a string. Now what is the fastest way to convert it back to an array?
谢谢!
推荐答案
我不确定这是最快的,但绝对是最安全/最简单的方法:
I'm not sure that this is the fastest, but it's definitely the safest/easiest:
import ast
lst = ast.literal_eval(s)
常规eval
也会起作用:
lst = eval(s)
我的机器上的一些基本时间:
Some basic timings from my machine:
>>> s = '[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]'
>>> def f1():
... eval(s)
...
>>> def f2():
... ast.literal_eval(s)
...
>>> timeit.timeit('f1()', 'from __main__ import f1')
31.415852785110474
>>> timeit.timeit('f2()', 'from __main__ import f2')
46.25958704948425
因此,根据我的计算机,eval
大约比ast.literal_eval
快50%.但是,eval
绝对不安全,除非您完全信任它,否则切勿在任何字符串上使用它.除非这是一个真正的演示瓶颈,并且您100%相信输入内容,否则我会认为值得花一点额外的时间来换取能够在晚上安然入睡的条件.
So, according to my computer, eval
is about 50% faster than ast.literal_eval
. However, eval
is terribly unsafe and should never be used on any string unless you trust it completely. Unless this is a real demonstratable bottleneck and you trust the input 100%, I would consider the little bit of extra time worth it in exchange for being able to sleep soundly at night.
这篇关于在python中将字符串转换为数组的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!