2013-07-31 54 views
1

R我能做到這一點切片Python列表VS切片[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 

我想有這樣做對Python(2.7)名單同樣優雅的方式,但還沒有找到。我對a[-b]位特別感興趣。有什麼想法嗎?

[編輯] 被[10,11,12,13,14,15,16,17,18,19],b爲[4,7](指數成)

+2

我會告訴你,如果我知道了''和'b'看起來像,'c()'意味着什麼。 – 2rs2ts

+0

@ 2rs2ts:編輯後向你展示「a」和「b」是什麼; 'c()'用於連接。在python中,'a = range(10,20)'和'b = [4,7]'。 – djas

回答

2

你做這個應用列表解析

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

或者使用numpy的:

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

x[y] 
+0

@JoranBeasley對吧!我發誓我就是這樣寫的! :) – Justin

+0

+1好答案,實際上是唯一真正有效的答案 –

+0

@Justin糾正我,如果我錯了,但numpy解決方案的問題是我們不能'x [-y]',或者我們可以? – djas

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

不是很高貴,但不做評論,也不會工作,如果有複製列表中的元素...因爲它在否定一步看值,而不是指數

+0

+1我喜歡你的名字。 – joran

0

你可能想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])