Shihui Guo

Access Multiple Elements in Python List

Say you are faced with a list and want to access selected elements inside it, here is the way:

#just put the required indexes in the parathesis at the end
selectedEle = [LIST[i] for i in [2, 4, 5]]

If you want to access the same pattern in a 2D list, then do this

# j is the upper level of the list, just like double-layered for loop
selectedEle = [2DLIST[j][i] for j in [4,5, 7] for i in [2, 4, 5]]

But the previous code returns all the elements in a single list, if you want to maintain the original two-layered list, do this

# Please note now, the iterator j is put at the end of the command
selectedEle = [[2DLIST[j][i] for i in [2, 4, 5] for j in [4,5, 7]]]

Python is elegant!

点击查看评论