2016-02-04 174 views
0
samplelist = [100,101,102,103,104,105,106,107,108,109] 

那麼我想輸出如下:如何打印列表跳過Python中,每次一個元素?

[100,[101,102,103,104,105,106,107,108,109]] 
[101,[100,102,103,104,105,106,107,108,109]] 
[102,[100,101,103,104,105,106,107,108,109]] 

在這裏與他人,我能夠產生

[101, 102, 103, 104, 105, 106, 107, 108, 109] 
[100, 102, 103, 104, 105, 106, 107, 108, 109] 
[100, 101, 103, 104, 105, 106, 107, 108, 109] 
[100, 101, 102, 104, 105, 106, 107, 108, 109] 

與下面的代碼的幫助:

[[el for el in samplelist if el is not i] for i in samplelist] 

但我想該號碼也跳到了前面,如上所示。 請建議更改該代碼。

+0

鏈接到前面的問題http://stackoverflow.com/questions/35194974/how-to-print-list-skipping-one-元素每個時間 - 在 - python的 - 不 - numpy的 –

+0

你爲什麼問同樣的問題相隔3個小時?如果第一個問題沒有得到很好的答案,你應該編輯的問題,以使其更清晰,不得發佈相同的問題。 – Barmar

回答

3

您可以創建一個嵌套列表與列表理解太:

>>> samplelist = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109] 
>>> newlist = [[item, [el for el in samplelist if el != item]] for item in samplelist] 
>>> for item in newlist: 
...  print(item) 
... 
[100, [101, 102, 103, 104, 105, 106, 107, 108, 109]] 
[101, [100, 102, 103, 104, 105, 106, 107, 108, 109]] 
[102, [100, 101, 103, 104, 105, 106, 107, 108, 109]] 
[103, [100, 101, 102, 104, 105, 106, 107, 108, 109]] 
[104, [100, 101, 102, 103, 105, 106, 107, 108, 109]] 
[105, [100, 101, 102, 103, 104, 106, 107, 108, 109]] 
[106, [100, 101, 102, 103, 104, 105, 107, 108, 109]] 
[107, [100, 101, 102, 103, 104, 105, 106, 108, 109]] 
[108, [100, 101, 102, 103, 104, 105, 106, 107, 109]] 
[109, [100, 101, 102, 103, 104, 105, 106, 107, 108]] 

BTW,你應該使用==比較值,而不是is。後者用於檢查對象的身份。事實上,你的代碼只能工作,因爲Python緩存小整數,這是一個實現細節。

-1
print [[i]+[el for el in samplelist if el is not i] for i in samplelist] 

有效嗎?

0

使用你的代碼,只需添加元素 '我':

>>> import pprint 
>>> x = [[i,[el for el in samplelist if el is not i]] for i in samplelist] 
>>> pprint.pprint(x) 
[[100, [101, 102, 103, 104, 105, 106, 107, 108, 109]], 
[101, [100, 102, 103, 104, 105, 106, 107, 108, 109]], 
[102, [100, 101, 103, 104, 105, 106, 107, 108, 109]], 
[103, [100, 101, 102, 104, 105, 106, 107, 108, 109]], 
[104, [100, 101, 102, 103, 105, 106, 107, 108, 109]], 
[105, [100, 101, 102, 103, 104, 106, 107, 108, 109]], 
[106, [100, 101, 102, 103, 104, 105, 107, 108, 109]], 
[107, [100, 101, 102, 103, 104, 105, 106, 108, 109]], 
[108, [100, 101, 102, 103, 104, 105, 106, 107, 109]], 
[109, [100, 101, 102, 103, 104, 105, 106, 107, 108]]] 
相關問題