简体   繁体   English

使用int而不是eval的多个输入

[英]multiple inputs using int instead of eval

Small question: Why doesn't this piece of code work when I use int but does when I use eval ? 小问题:为什么当我使用int时这段代码不起作用,而当我使用eval时却行吗? int can only take one input? int只能接受一个输入? Is there a way to make it take multiple inputs as concise as using eval? 有没有办法使它像使用eval一样简洁地接受多个输入? Int is a stronger condition so that's why I am curious about how it would work. 整数是一个更强的条件,所以这就是为什么我对它如何工作感到好奇的原因。

a,b,c = int(input("enter numbers: "))
print(no_teen_sum(a,b,c))

This gives ValueError: invalid literal for int() with base 10 , but the following code does work. 这会给ValueError: invalid literal for int() with base 10 ,但以下代码确实可以工作。

a,b,c = eval(input("enter numbers: "))
print(no_teen_sum(a,b,c))

int takes one input and possibly a base: int接受一个输入,可能还需要一个基数:

>>> int('46',7) # 46 is 34 in base 7

34

But you can use int along with map : 但是您可以将intmap一起使用:

>>> map(int,['1','2','3'])

[1, 2, 3]

Use list comprehension: 使用清单理解:

def main():
    numbers = input("enter numbers: ").split()
    print(no_teen_sum(*[int(n) for n in numbers)])

main()

Python is trying to parse the whole string as one integer rather than three. Python试图将整个字符串解析为一个整数而不是三个整数。

What you could do is: 您可以做的是:

a, b, c = map(int, input("enter numbers: ").split())

This way you are splitting the list into three strings, and then converting (mapping) each string to an int. 这样,您可以将列表分为三个字符串,然后将每个字符串转换(映射)为一个int。

int can only take one input? int只能接受一个输入?

Yes, and that is technically true for eval , too. 是的,对于eval在技​​术上也是如此。 It's just that eval might return something other than an int . 只是eval可能返回int以外的其他值。 In your case, I'm assuming you enter something like 1, 2, 3 on the input prompt. 对于您的情况,我假设您在input提示中输入类似于1, 2, 3 eval simply parses that as a tuple, which it returns, and unpacks into your three variables. eval只是将其解析为元组,然后返回,然后解压缩为三个变量。

You can, however, easily achieve something similar to what you want using list comprehension: 但是,您可以使用列表推导轻松实现与您想要的目标相似的目标:

a, b, c = [int(x.strip()) for x in input("Enter numbers: ").split(",")]

This has the added benefit that you don't risk having some completely unexpected type returned from eval . 这具有额外的好处,您不必冒险从eval返回某些完全意外的类型。

One caveat with using eval that should perhaps be worth noting is that it accepts any valid Python syntax and executes the parsed result, which may include arbitrary function calls, including code to erase your hard drive. 使用eval可能需要注意的一个警告是,它接受任何有效的Python语法并执行已解析的结果,该结果可能包括任意函数调用,包括擦除硬盘的代码。 Not much of a problem when you're just writing a program for yourself to use, but just so that you know. 当您只是编写一个供自己使用的程序时,这没什么大问题,只是您知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM