Вопрос

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']
[]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top