Python 重写函数作为嵌套列表理解
如何将上述函数编写为一行程序 失败的尝试:Python 重写函数作为嵌套列表理解,python,python-3.x,nested,Python,Python 3.x,Nested,如何将上述函数编写为一行程序 失败的尝试: 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)) 注:请保留实用性和可读性评论。谢谢。如我在评论中所述,您基本上是在重新
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))
注:请保留实用性和可读性评论。谢谢。如我在评论中所述,您基本上是在重新实现
索引
当前函数返回搜索项第一次出现的索引,如果未找到,则返回None
作为一个列表理解(为了学术的缘故),这可能看起来像:
def col_num_of(columnName,listObj):
return ind if cell==columnName for ind,cell in enumerate(listObj)
如果要查找的值不在列表中,则.index()将为您提供ValueError
>>> alist=['a','b','Date','e','f']
>>> alist.index('Date')
2
>>> [i for i, v in enumerate(alist) if v=='Date']
[2]
>>>alist=['a','b','Date','e','f']
>>>列表索引('acc')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
列表索引('acc')
ValueError:“acc”不在列表中
此外,如果要查找的字符串多次出现,则只会得到第一个字符串
>>> 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
>>>alist=['a','b','a']
>>>列表索引('a')
0
因此,要么确保捕获此错误,要么使用dawg提供的方法:
>>> alist=['a','b','a']
>>> alist.index('a')
0
>>>[i表示i,如果v=='Date',枚举(列表)中的v]
[2]
如果没有匹配项,则返回空列表
>>> [i for i, v in enumerate(alist) if v=='Date']
[2]
>>>[i表示i,如果v=='accc',枚举(列表)中的v]
[]
['a'、'b'、'Date'、'e'、'f'].索引('Date')
?非常感谢您的帮助。出于教育目的,有没有正确的方法来写我失败的尝试?这实际上与OP的函数做的事情不一样,但它确实为他指明了正确的方向。
>>> [i for i, v in enumerate(alist) if v=='Date']
[2]
>>> [i for i, v in enumerate(alist) if v=='accc']
[]