<分区>
有没有办法用 lambda 将这个 try/except 简化为一行?
alist = ['foo','bar','duh']
for j,i in enumerate(alist):
try:
iplus1 = i+alist[j+1]
except IndexError:
iplus1 = ""
还有其他方法吗:
j = '' if IndexError else trg[pos]
<分区>
有没有办法用 lambda 将这个 try/except 简化为一行?
alist = ['foo','bar','duh']
for j,i in enumerate(alist):
try:
iplus1 = i+alist[j+1]
except IndexError:
iplus1 = ""
还有其他方法吗:
j = '' if IndexError else trg[pos]
最佳答案
不,Python 对 try
/except
语法没有任何简写或简化。
为了解决您的具体问题,我可能会使用类似的方法:
for j, i in enumerate(alist[:-1]):
iplus1 = i + alist[j + 1]
这将避免异常的需要。
或者变得 super 酷和通用:
from itertools import islice
for j, i in enumerate(islice(alist, -1)):
iplus1 = i + alist[j + 1]
或者,您可以使用:itertools.iziplongest
来做类似的事情:
for i, x in itertools.izip_longest(alist, alist[1:], fillvalue=None):
iplus1 = i + x if x is not None else ""
最后,关于命名法的一个小注意事项:i
传统上用于表示“索引”,因此使用 for i, j in enumerate(...)
会更“正常”。
关于python - 只是用 lambda 尝试/排除 - Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208910/