alv*_*vas 2 python lambda try-except
有没有办法简化这个尝试/除了与lambda一行?
alist = ['foo','bar','duh']
for j,i in enumerate(alist):
try:
iplus1 = i+alist[j+1]
except IndexError:
iplus1 = ""
Run Code Online (Sandbox Code Playgroud)
还有其他方式:
j = '' if IndexError else trg[pos]
Run Code Online (Sandbox Code Playgroud)
不,Python没有try
/ except
syntax的任何简短或简化.
为了解决您的具体问题,我可能会使用以下内容:
for j, i in enumerate(alist[:-1]):
iplus1 = i + alist[j + 1]
Run Code Online (Sandbox Code Playgroud)
这将避免需要例外.
或者获得超酷和通用:
from itertools import islice
for j, i in enumerate(islice(alist, -1)):
iplus1 = i + alist[j + 1]
Run Code Online (Sandbox Code Playgroud)
另外,你可以使用:itertools.iziplongest
做类似的事情:
for i, x in itertools.izip_longest(alist, alist[1:], fillvalue=None):
iplus1 = i + x if x is not None else ""
Run Code Online (Sandbox Code Playgroud)
最后,关于命名法的一个小注释:i
传统上用于表示"索引",因此使用for i, j in enumerate(…)
将更"正常".
归档时间: |
|
查看次数: |
5526 次 |
最近记录: |