how to print list skipping one element each time in python without numpy?

前端 未结 3 1816
既然无缘
既然无缘 2021-01-20 08:03

given

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

then I want output as below:

[100,[101,102,103,104,105,106,10         


        
3条回答
  •  感动是毒
    2021-01-20 08:18

    You can use a simple slicing within a list comprehension :

    >>> [samplelist[:i]+samplelist[i+1:] for i,_ in enumerate(samplelist)]
    [[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],
     [100, 101, 102, 103, 105, 106, 107, 108, 109],
     [100, 101, 102, 103, 104, 106, 107, 108, 109],
     [100, 101, 102, 103, 104, 105, 107, 108, 109],
     [100, 101, 102, 103, 104, 105, 106, 108, 109],
     [100, 101, 102, 103, 104, 105, 106, 107, 109],
     [100, 101, 102, 103, 104, 105, 106, 107, 108]]
    

    If you want to capture the omitted item :

    >>> [[samplelist[i],samplelist[:i]+samplelist[i+1:]] for i,_ in enumerate(samplelist)]
    [[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]]]
    

提交回复
热议问题