简体   繁体   中英

First element in list/nested lists

I have a list, which can either be list[] or list[][] , and I want to get the very first actual element, which is either list[0] or list[0][0] . What would be the most pythonic way to do this?

You can try

ls[0][0] if isinstance(ls[0], list) else ls[0]

This will return the ls[0][0] if ls containing a list in the first value else the first value of the ls .

The suggested methods will work in your case, but let me suggest a more generic method:

elem = mylist
while type(elem) == list:
    elem = elem[0]

At the end of this loop, elem will contain the first element.

It will achieve the objective for even higher dimensional lists, or even non-list objects (it will just not run the loop at all).

Straightforward approach is most Pythonic here:

elem = mylist[0]
if isinstance(elem, list):
    elem = elem[0]

If a dimension might be length zero, this will raise an IndexError , but that's probably what you want anyway.

You can do this:

try:
    print(l[0][0])
except:
    print(l[0])

Something like this,

l1=[1]

try:
    a=l1[0][0]
    print("two diamensional")
except:
    print("one diamensional")

hope this helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM