Accessing non-consecutive elements of a list or string in python

后端 未结 5 1985
难免孤独
难免孤独 2020-12-28 15:14

As far as I can tell, this is not officially not possible, but is there a \"trick\" to access arbitrary non-sequential elements of a list by slicing?

For example:

5条回答
  •  礼貌的吻别
    2020-12-28 16:08

    Just for completeness, the method from the original question is pretty simple. You would want to wrap it in a function if L is a function itself, or assign the function result to a variable beforehand, so it doesn't get called repeatedly:

    [L[x] for x in [2,5]]
    

    Of course it would also work for a string...

    ["ABCDEF"[x] for x in [2,0,1]]
    ['C', 'A', 'B']
    

提交回复
热议问题