【问题标题】:Why does slice(10, 50, 2).indices(10) return (10, 10, 2)?为什么 slice(10, 50, 2).indices(10) 返回 (10, 10, 2)?
【发布时间】:2015-04-17 22:05:43
【问题描述】:
#!/usr/bin/python
# 1.11. Naming a Slice
# Problem: Your program has become an unreadable mess of 
# hardcoded slice indices and you want to clean it up.

###### 0123456789012345678901234567890123456789012345678901234567890'
record = '....................100          .......513.25   ..........'  
cost = int(record[20:32]) * float(record[40:48])

print (cost)

# name the slices
SHARES = slice(20,32)
PRICE = slice(40,48)

cost = int(record[SHARES]) * float(record[PRICE])
print (cost)


items = [0, 1, 2, 3, 4, 5, 6]
a = slice(2, 4)

print (items[2:4])
print (items[a])

items[a] = [10,11]
print (items)

del items[a]
print (items)


a = slice(10, 50, 2)
print (a.start, a.stop, a.step)


s = 'HelloWorld'
indice = a.indices(len(s))
print (indice)

for i in range(*a.indices(len(s))):
    print(s[i])

这是 Python Cookbook 第 1.11 章中的示例。

print (indices)

这应该给我(5,10,2),但它给了我(10,10,2)。然后下面的for循环没有打印任何东西。

为什么我的代码显示的结果和书中的不一样?

【问题讨论】:

  • a 定义为什么?
  • @MattDMo a 应该定义为什么?在我之前的代码中其实是定义为 a=slice(10,50,2) -_-!
  • 请阅读MCVEs。您需要发布重现问题所需的完整代码,包括定义导入和所有对象
  • @MattDMo slice() 是一个内置的python
  • @mata derp。我会编辑...

标签: python python-3.x indices


【解决方案1】:

这实际上是书中的一个错误。如果你查看errata 并向下滚动到第 19 页,就会有这样的描述:

这个示例“a.indices(len(s))”导致的输出与书中打印的输出不同,假设切片 a 是上面示例中所示的切片 a。如果 a 是 slice(5, 50, 2) 左右,它将以所示方式工作。还是我错了?

作者或编者注: 将示例中间页面更改为:

>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>

底部的问题示例应该可以工作。

【讨论】:

  • 非常感谢。这个错误链接真的很有帮助。
  • @fluency_03 没问题。所有 O'Reilly 的书都有,只需在他们的网站上搜索该书,转到其页面,然后在“基本链接”框中右键单击“查看/提交勘误表”,即可查看。跨度>
猜你喜欢
  • 2011-10-26
  • 1970-01-01
  • 2021-03-15
  • 2023-03-04
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2011-11-04
相关资源
最近更新 更多