【问题标题】:xlrd: Why is end_colx 1-indexed when start_colx is 0-indexed?xlrd:当 start_colx 为 0 索引时,为什么 end_colx 为 1 索引?
【发布时间】:2014-06-02 11:17:20
【问题描述】:

给定一个具有以下布局的 Excel 工作表:

  A                    | B
1 Name of First Column | Name of Second Column
2 Value in First Column| Value in Second Column

xlrd 肯定有一种奇怪的索引方式。首先,一些设置...

import xlrd
f = open("example.xlsx")
wb = xlrd.open_workbook(file_contents=f.read())
sh = wb.sheet_by_index(0)

让我们看看使用row_values的第一行是什么

print sh.row_values(0, start_colx=0, end_colx=1)

结果?

[u'Name of First Column']

出了什么问题? row_values 的第一个未标记参数是 rowx"'rowx' is a row index, counting from zero" 还有两个colx"'colx' is a column index, counting from zero."

你可能会想,colx 都应该从零开始计数。如果我在end_colx 中指定,我想在1 列结束,我的意思是第二列,从零开始计数。

【问题讨论】:

    标签: python xlrd


    【解决方案1】:

    xlrd 观察到的行为让我想起了 python 的切片符号,它是这样的:

     +---+---+---+---+---+
     | H | e | l | p | A |
     +---+---+---+---+---+
     0   1   2   3   4   5
    -5  -4  -3  -2  -1
    

    (给定一串“HelpA”——that's from the official docs

    因此,如果您从 0 开始并以 0 ([0:0]) 结束,您将不会检索到任何内容。

    如果有人有更好的答案,我很想听听。只是想记录一下。

    【讨论】:

    • 我很确定这是正确的答案。您为row_values 链接到的文档说Returns a slice of the values of the cells in the given row,因此边界的工作方式与Python 切片的工作方式相同。 “结束”索引实际上是“刚刚结束”。如果要切到行尾,请将None 传递为end_colx(或者直接跳过参数,因为None 是默认值)。
    猜你喜欢
    • 2019-09-15
    • 2019-09-05
    • 2019-03-12
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多