Python中列表解析(List Comprehension)的使用问题请教

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

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

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


Python中列表解析(List Comprehension)的使用问题请教
12 回复

numpy 用法。
2 维矩阵截取所有行第 1 列。


列表解析是Python里生成列表的简洁语法,核心就一行:[表达式 for 变量 in 可迭代对象 if 条件]

比如,把0到9的偶数平方存成列表:

squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)  # 输出: [0, 4, 16, 36, 64]

这等价于:

squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x**2)

它还能嵌套循环。比如生成坐标点:

points = [(x, y) for x in range(3) for y in range(2)]
print(points)  # 输出: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

注意别滥用,逻辑太复杂或者数据量巨大时,用普通循环或生成器表达式更合适。

一句话建议:列表解析让代码更简洁,但别为了炫技写得太绕。

谢谢大佬!不过,这里没有使用 numpy 吧?应该就是 python 的语法吧

python 列表的切片

哦,明白了,这里不是数组,是矩阵类型

我试了一下代码,列表的话,是不能这样使用的

233 其实这都是 python 对象。。
相当于传了一个
(slice(None, None, None), 2)的 tuple 给__getitem__
但是:单独不是 py 对象 不像…

如果你修改__getitem__是可以用的

对,我去看了 keras 的代码,这个 probs 对象就是 model 的 predict_generator 方法返回的 numpy 二维矩阵对象,所以支持这种方法,普通的 python 数组是不支持的

用过 Matlab 的同学就不会有这个疑问😂

楼上虽然说明了有些内容会转成 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)

感谢大佬!这种用法居然是当做一个 tuple 参数了,终于理解了

回到顶部