简体   繁体   中英

Rewriting function as nested list comprehension

alist['a','b','Date','e','f']

def col_num_of(columnName,listObj):
    for ind,cell in enumerate(listObj):
        if cell==columnName:
            return ind

print(col_num_of('Date',alist))

How to write the above function as a one liner?

Failed Attempt:

def col_num_of(columnName,listObj):
    return ind if cell==columnName for ind,cell in enumerate(listObj)

Note: Please hold practicality and readability comments. Thank you.

As stated in my comment, you are basically reimplementing index .

You current function returns the index of the first occurence of the searched item, or None if it is not found.

As a list comprehension (just for academica's sake) this could look like:

colNum = ([idx for idx, ele in enumerate(alist) if ele == 'Date'] + [None])[0]
>>> alist=['a','b','Date','e','f']
>>> alist.index('Date')
2
>>> [i for i, v in enumerate(alist) if v=='Date']
[2]

.index() will give you ValueError if the value you're looking for is not in the list.

>>> alist=['a','b','Date','e','f']
>>> alist.index('acc')

Traceback (most recent call last):
  File "", line 1, in 
    alist.index('acc')
ValueError: 'acc' is not in list

Also if you have multiple occurrence of the string you're looking for, you will only get the first one.

>>> alist=['a','b','a']
>>> alist.index('a')
0

So either make sure you'll catch this error, or you can use the method by dawg:

>>> [i for i, v in enumerate(alist) if v=='Date']
[2]

This will return empty list if no matches.

>>> [i for i, v in enumerate(alist) if v=='accc']
[]

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