繁体   English   中英

有人帮我理解以下Python代码中的方括号吗?

[英]Someone help me understand the square bracket in the following Python code?

import xlrd
book = xlrd.open_workbook("univ_list.xls")
sh = book.sheet_by_index(0)
for r in range(sh.nrows)[1:]: # line 4
    print sh.row(r)[:4] # line 5

[1:]在第4行中表示什么? [:4]在第5行中表示什么?

这是您在Wikipedia上看到的示例: http : //en.wikipedia.org/wiki/Array_slicing#1991 : _Python

这称为数组切片。 [1:]获取除第一个项目外的所有项目, [:4]获取前四个项目。

[1:]表示您只想从列表中的位置1,字符串等中获取项目。

[:4]表示您要查询字符串或列表中的项目4。

请记住,编号从0开始。

因此在f ='apple',f [0] ='a',f [1] ='p',f [1:] ='pple'

阅读切片符号-您可以做更多的事情。

暂无
暂无

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

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