加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-3.x – 何时使用ast.literal_eval

发布时间:2020-12-20 11:42:07 所属栏目:Python 来源:网络整理
导读:我遇到了这个代码并且它可以工作,但我不完全确定何时使用ast以及是否存在性能问题,而不是从input()获取字符串值并将其转换为int. import astcyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))# this get the user input
我遇到了这个代码并且它可以工作,但我不完全确定何时使用ast以及是否存在性能问题,而不是从input()获取字符串值并将其转换为int.

import ast

cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))

# this get the user input as an int to the variable cyper_key

我阅读了我理解它的作用的文档.

This can be used for safely evaluating strings containing Python
values from untrusted sources without the need to parse the values
oneself. It is not capable of evaluating arbitrarily complex
expressions,for example involving operators or indexing.

我正在寻找上述大胆点的解释.

解决方法

什么时候使用它.

如果您期望用户使用列表(或类似内容),ast.literal_eval(input())将非常有用.例如,'[1,2]’将被转换为[1,2].

如果用户应该提供一个数字ast.literal_eval(input())可以用float(input())或int(input())替换,如果需要一个整数.

性能:

要测试ast.literal_eval(input())和float(input()的速度,可以使用timeit.

时间将根据用户给出的输入而变化.

Ints和float是有效的输入,而其他任何东西都是无效的.给出50%的整数,40%的浮点数和10%的随机值作为输入,float(input())的速度提高了x12.

使用10%,10%,80%和float(input())更快x6.

import timeit as tt

lst_size = 10**5

# Set the percentages of input tried by user.
percentages = {'ints': .10,'floats': .10,'strings': .80}
assert 1 - sum(percentages.values()) < 0.00000001

ints_floats_strings = {k: int(v*lst_size) for k,v in percentages.items()}

setup = """
import ast

def f(x):
    try:
        float(x)
    except:
        pass

def g(x):
    try:
        ast.literal_eval(x)
    except:
        pass

l = [str(i) for i in range({ints})]
l += [str(float(i)) for i in range({floats})]
l += [']9' for _ in range({strings}//2)] + ['a' for _ in range({strings}//2)]
""".format(**ints_floats_strings)

stmt1 = """
for i in l:
    f(i)
"""

stmt2 = """
for i in l:
    g(i)
"""


reps = 10**1
t1 = tt.timeit(stmt1,setup,number=reps)
t2 = tt.timeit(stmt2,number=reps)

print(t1)
print(t2)

print(t2/t1)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读