简体   繁体   English

在 python 中切片类似于 MATLAB

[英]Slicing in python similar to MATLAB

In Matlab, slice can be a vector:在 Matlab 中, slice 可以是一个向量:

a = {'a','b','c','d','e','f','g'}; % cell array
b = a([1:3,5,7]);

How can I do the same thing in python?我怎样才能在 python 中做同样的事情?

a = ['a','b','c','d','e','f','g']
b = [a[i] for i in [0,1,2,4,6]]

but when 1:3 becomes 1:100, this will not work.但是当 1:3 变成 1:100 时,这将不起作用。 Using range(2),4,6 returns ([0,1,2],4,6), not (0,1,2,4,6).使用 range(2),4,6 返回 ([0,1,2],4,6),而不是 (0,1,2,4,6)。 Is there a fast and "pythonic" way?有没有一种快速且“pythonic”的方式?

If you want to do things that are similar to Matlab in Python, NumPy should always be your first guess.如果你想做类似于 Python 中的 Matlab 的事情,NumPy 应该总是你的第一个猜测。 In this case, you need numpy.r_ :在这种情况下,您需要numpy.r_

from numpy import array, r_
a = array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print a[r_[1:3, 5, 7]]

['b' 'c' 'f' 'h']

One way is using itertools.chain :一种方法是使用itertools.chain

>>> b = [a[i] for i in itertools.chain(range(2), [5, 6])]
>>> b
['b', 'c', 'f', 'g']

Notes:笔记:

  1. Ranges adapted from Matlab (1-based indexing) to Python (0-based indexing)范围从 Matlab(基于 1 的索引)到 Python(基于 0 的索引)
  2. You may gain by changing range to xrange if you have Python 2.x, to avoid creating the whole range list on the fly.如果您有 Python 2.x,您可以通过将range更改为xrange来获得收益,以避免动态创建整个范围列表。 I don't think it will make a big performance difference, but it's nice to know about.我认为这不会产生很大的性能差异,但很高兴知道。

Try尝试

[a[i] for i in range(2) + [4, 6]]

If you use NumPy, then you have some more options:如果您使用 NumPy,那么您还有更多选择:

import numpy as N
a = N.array(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
b = a[range(2) + [4, 6]]
c = a.take(range(2) + [4, 6])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM