为什么索引为负的sys.argv应该允许打印与sys.argv相同的值?同样,它允许传递的参数数量最多。
因此,调用developers.google.com上的hello.py,如下所示(带有3个参数,包括脚本名称):python hello.py Sumit测试
将允许访问sys.argv-1、-2和-3,并且它们都打印与argv相同的值,即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代码是:
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()发布于 2013-06-11 14:36:28
因为您只传递了三个参数,所以下面的示例应该可以帮助您理解:
>>> [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负索引从右侧打印一个值。
Accessing Lists
例如,我们的数组/列表的大小为n,那么对于正索引,0是第一个索引,1是第二个索引,最后一个索引将是n-1。对于负指数,-n是第一个指数,-(n-1)第二个,最后一个负指数将是–1。
根据您的评论,我添加了一个示例以供澄清:
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]请观察输出:
$ python main.py one two
3
two one main.py
main.py one two传递的参数数量是三个。argv[-1]是最后一个参数,即two
发布于 2013-06-11 14:36:32
负数索引从列表末尾开始计数:
>>> ['a', 'b', 'c'][-1]
'c'
>>> ['a', 'b', 'c'][-2]
'b'
>>> ['a', 'b', 'c'][-3]
'a'请求-4将从列表的末尾消失,给出一个例外。
https://stackoverflow.com/questions/17037818
复制相似问题