请教一个 Python 列表解析的问题

2017-11-21 11:07:46 +08:00
 winglight2016

代码:our_predictions = probs[:,0],

这一句里面的冒号是什么作用? probs 是个二维数组吧?

我问了个朋友,他说这是列表解析的语法,但是他也说不清楚,请教一下高手这一句是在做什么? BTW,这是在看深度学习时候碰到的代码

2340 次点击
所在节点    Python
11 条回复
enenaaa
2017-11-21 11:33:10 +08:00
numpy 用法。
2 维矩阵截取所有行第 1 列。
winglight2016
2017-11-21 11:44:21 +08:00
@enenaaa 谢谢大佬!不过,这里没有使用 numpy 吧?应该就是 python 的语法吧
8820670
2017-11-21 11:45:19 +08:00
@winglight2016 python 列表的切片
winglight2016
2017-11-21 11:48:47 +08:00
@enenaaa 哦,明白了,这里不是数组,是矩阵类型
winglight2016
2017-11-21 11:49:36 +08:00
@8820670 我试了一下代码,列表的话,是不能这样使用的
lrxiao
2017-11-21 12:18:05 +08:00
233 其实这都是 python 对象。。
相当于传了一个
(slice(None, None, None), 2)的 tuple 给__getitem__
但是:单独不是 py 对象 不像...
lrxiao
2017-11-21 12:18:28 +08:00
如果你修改__getitem__是可以用的
winglight2016
2017-11-21 12:52:36 +08:00
@lrxiao 对,我去看了 keras 的代码,这个 probs 对象就是 model 的 predict_generator 方法返回的 numpy 二维矩阵对象,所以支持这种方法,普通的 python 数组是不支持的
bigeast
2017-11-21 13:36:30 +08:00
用过 Matlab 的同学就不会有这个疑问😂
siteshen
2017-11-21 22:05:45 +08:00
楼上虽然说明了有些内容会转成 tuple,不过以前没见过这种写法,还是不清楚是怎么转成 tuple 的,就研究了下。

https://docs.python.org/3/reference/expressions.html#slicings

The semantics for a slicing are as follows. The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section The standard type hierarchy) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions.

对于表达式 a[`.+`] 如果 正则 `.+` 至少包含一个逗号,则 key 为一个 tuple,否则 key 为 slice。
下面的示例能更清楚地说明上面的规则:

$ cat test.py && python3 test.py
class A():
def __getitem__(self, *args, **kwargs):
print('args:', len(args), args[0])

a = A()
a[1:]
a[:2]
a[1:2]
a[1,:]
a[:,2]
a[1,:,2]
# end of test.py

args: 1 slice(1, None, None)
args: 1 slice(None, 2, None)
args: 1 slice(1, 2, None)
args: 1 (1, slice(None, None, None))
args: 1 (slice(None, None, None), 2)
args: 1 (1, slice(None, None, None), 2)
winglight2016
2017-11-22 11:56:56 +08:00
@siteshen 感谢大佬!这种用法居然是当做一个 tuple 参数了,终于理解了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/408183

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX