列表和元组不同的行为 [英] List and tuple behave differently

查看:220
本文介绍了列表和元组不同的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我清楚地知道,有列表和元组和的元组并不只是不断名单的,但也有其中两个实际上是由 code 的(由编码约定反对),所以我(拖泥带水)都可以互换使用它们。

I'm well aware that there are differences between lists and tuples and that tuples aren't just constant lists, but there are few examples where the two are actually treated differently by the code (as opposed to by a coding convention), so I (sloppily) have used them interchangeably.

那时,我发现他们给完全不同的行为为例来了

Then I came across a case where they give totally different behavior:

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

有人能解释这是怎么回事呢?更重要的是,还有什么地方没有这个陷阱出现在SciPy的?

can someone explain what's going on here? More importantly, where else does this pitfall appear in scipy?

推荐答案

您已经看到了不同的行为,因为在numpy的,三种类型的索引都支持

You are getting a different behavior because, in numpy, three types of indexing are supported


  • 基本切片

  • 高级索引

  • 记录访问

索引使用元组仅仅是相当于一个参数列表,其后缀为基本切片,在这里,由于使用非元组像高级索引列表的结果。

Using tuple for indexing is just equivalent to a parameter list, which suffixes as a Basic Slicing, where-as using a non-tuple like list results in Advanced Indexing.

还记得,从文档

高级索引时触发的选择对象obj是一个
  非元组序列对象,ndarray的(数据类型整数或布尔)
  或与至少一个序列的对象或ndarray(的数据类型的元组
  整数或布尔)。有两种类型的高级索引:整数
  和布尔。

Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean.

高级索引总是返回数据的副本(与对比
  返回一个观点基本切片)。

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

和此外,从相同的文档

在Python中,×[(EXP1,EXP2,...,EXPN)]等价于x [EXP1,EXP2,
  ...,EXPN]后者是前者只是语法糖。

In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former.

这篇关于列表和元组不同的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆