gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:59:39 24 4
gpt4 key购买 nike

我遇到了这个代码并且它有效,但我不完全确定 何时使用 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())如果需要一个整数。

性能

请注意 premature [micro-]optimization is the root of all evil.但既然你问:

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

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

整数和浮点数是有效的输入,而其他任何东西都是无效的。输入 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, setup, number=reps)

print(t1)
print(t2)

print(t2/t1)

关于python-3.x - 何时使用 ast.literal_eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com