简体   繁体   English

如何将 sys.argv 列表元素从字符串更改为整数?

[英]How to change sys.argv list elements from strings to ints?

So I tried to convert a list of strings:所以我尝试转换字符串列表:

['25', '-36', '85', '94', '21', '-68', '-55', '24']

into a list of ints like:进入一个整数列表,如:

[25, -36, 85, 94, 21, -68, -55, 24] 

So what I did is:所以我所做的是:

for i in range(len(sys.argv)):
    if isinstance(sys.argv[i], int) == True:
        sys.argv[i] = int(sys.argv[i])

But I'm not sure why the items in list are still strings...can someone explain?但我不确定为什么列表中的项目仍然是字符串......有人可以解释一下吗?

Items in sys.argv are always string instances when the interpreter loads, so the test isinstance(sys.argv[i], int) would always return False . sys.argv中的项目在解释器加载时始终是字符串实例,因此测试isinstance(sys.argv[i], int)将始终返回False

To convert arguments into integers only if they represent integers, you can instead use a try-except block around the integer conversion to ignore strings that do not represent integers:要将 arguments 仅在它们表示整数时转换为整数,您可以在 integer 转换周围使用try-except块来忽略不表示整数的字符串:

for i, s in enumerate(sys.argv):
    try:
        sys.argv[i] = int(s)
    except ValueError:
        pass

The reason why your code is not running is: it will never get into if statement .您的代码未运行的原因是:它永远不会进入if statement

if isinstance(sys.argv[i], int) will always return False since your input is a string. if isinstance(sys.argv[i], int)始终返回False ,因为您的输入是字符串。 And your comparison isinstance(sys.argv[i], int) == True will always return False either, because you are always comparing False == True for any values in your initial string list.并且您的比较isinstance(sys.argv[i], int) == True也将始终返回False ,因为您始终针对初始字符串列表中的任何值比较False == True


The most easy and fast way to make your conversion is using list comprehension:进行转换的最简单快捷的方法是使用列表推导:

l_str = ['25', '-36', '85', '94', '21', '-68', '-55', '24']

l_int = [int(x) for x in l_str]

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

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