如何打印每次在Python中跳过一个元素的列表?

时间:2016-02-04 10:21:32

标签: python list

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

然后我想要输出如下:

[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]

但是我想在前面跳过这个号码,如上图所示。 请建议更改该代码。

3 个答案:

答案 0 :(得分: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]]

顺便说一下,您应该使用==来比较值,而不是is。后者用于检查对象的身份。实际上,您的代码只能起作用,因为Python会缓存小整数,这是一个实现细节。

答案 1 :(得分:0)

使用您的代码,只需添加元素' i':

>>> 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]]]

答案 2 :(得分:-1)

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

作品?