[英]Python sys.argv negative argument index
Why should sys.argv with a negative index allow printing same value as sys.argv[0]? 为什么带负索引的sys.argv允许打印与sys.argv [0]相同的值? That too, it allows this up to number of arguments passed. 同样,它允许最多传递的参数数量。
So, a call to hello.py at developers.google.com, such as the one below (with 3 arguments including script name) : python hello.py Sumit Test 因此,在developers.google.com上调用hello.py,例如下面的那个(包含3个参数,包括脚本名称):python hello.py Sumit Test
would allow accessing sys.argv[-1], [-2] and [-3] with all of them printing the same value as argv[0] ie hello.py, but argv[-4] will throw the expected error: 将允许访问sys.argv [-1],[ - 2]和[-3],所有这些都打印与argv [0]相同的值,即hello.py,但是argv [-4]将抛出预期的错误:
Traceback (most recent call last):
File "hello.py", line 35, in <module>
main()
File "hello.py", line 31, in main
print (sys.argv[-4])
IndexError: list index out of range
The code is: 代码是:
import sys
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
if len(sys.argv) >= 2:
name = sys.argv[1]
else:
name = 'World'
print ('Hello', name)
print (sys.argv[-3])
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
Because you are passing only three arguments, my example below should help you understand: 因为您只传递了三个参数,所以下面的示例应该可以帮助您理解:
>>> [1,2,3][-1] # working
3
>>> [1,2,3][-2] # working
2
>>> [1,2,3][-3] # working
1
>>> [1,2,3][-4] # exception as in your code
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Negative index prints a value from the right hand side. 负指数从右侧打印一个值。
Accessing Lists 访问列表
For instance our array/list is of size n , then for positive indices 0
is the first index, 1
the second and the last index will be n-1
. 例如,我们的数组/列表的大小为n ,那么对于正索引, 0
是第一个索引, 1
是第二个索引,最后一个索引是n-1
。 For negative indices, -n
is the first index, -(n-1)
second, last negative index will be –1
. 对于负指数, -n
是第一个指数, -(n-1)
秒,最后一个负指数将是–1
。
On the basis of your comment, I am adding an example for clarification: 根据您的评论,我将添加一个示例来澄清:
import sys
# main()
if __name__ == "__main__":
print len(sys.argv)
print sys.argv[-1], sys.argv[-2], sys.argv[-3]
print sys.argv[0], sys.argv[1], sys.argv[2]
Please observe the output: 请观察输出:
$ python main.py one two
3
two one main.py
main.py one two
The number of arguments passed is three. 传递的参数数量为3。 argv[-1]
is the last argument, which is two
argv[-1]
是最后一个参数,它是two
Negative indexes count from the end of the list: 负索引从列表末尾开始计算:
>>> ['a', 'b', 'c'][-1]
'c'
>>> ['a', 'b', 'c'][-2]
'b'
>>> ['a', 'b', 'c'][-3]
'a'
Asking for [-4] would go off the end of the list, giving an exception. 要求[-4]将从列表的末尾开始,给出一个例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.