简体   繁体   English

切片Python列表与切片R矢量

[英]Slicing Python lists vs Slicing R vectors

In R I can do this R我可以做到这一点

> a = (10:19)
> a
 [1] 10 11 12 13 14 15 16 17 18 19
> b = c(4,7)
> b
[1] 4 7
>
> a[b]
[1] 13 16
>
> a[-b]
[1] 10 11 12 14 15 17 18 19

I suppose there is an equally elegant way of doing this to Python (2.7) lists, but haven't found yet. 我想有一个同样优雅的方式来做这个Python(2.7)列表,但还没有找到。 I'm particularly interested in the a[-b] bit. 我对a[-b]位特别感兴趣。 Any thoughts? 有什么想法吗?

[edit] a is [10,11,12,13,14,15,16,17,18,19], b is [4,7] (indices into a) [编辑] a是[10,11,12,13,14,15,16,17,18,19],b是[4,7](索引成a)

You do this using list comprehensions 您可以使用列表推导来完成此操作

[n for n, i in enumerate(a) if i not in b]

Or using numpy: 或使用numpy:

x = np.arange(10, 20)
y = [2, 7]

x[y]
 a=numpy.array(range(10,20))
 b = [4,7]
 print a[b]
 print a[~numpy.in1d(a,a[b])]

not quite as elegent but meh ... it also wont work if there are duplicate elements in the list ... since its looking at the values in the negation step rather than the indices 不是很优雅,但是......如果列表中有重复的元素,它也无法工作...因为它在否定步骤而不是索引中查看值

You probably want numpy: 你可能想要numpy:

import numpy as np
a = np.array(range(10,19))
b = [3,6]
a[b]
=> array([13, 16])
a[[_ for _ in range(len(a)) if _ not in b]]
=> array([10, 11, 12, 14, 15, 17, 18])

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

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