python 中的内联错误/异常处理
因此,我有 3 个列表,如下所示:
list_1 = ['a','b','c']
list_2 = ['b','c']
list_3 = [5,4]
我希望从 list_2 & 生成第四个值列表。 list_3 将映射到 list_1。 list_2 和 list_3 独立于 list_1,但都是 list_1 的子集并且相互映射。即list_2和list_3缺少项目'a'和相应的值。
我想处理缺失的值并分配一些值,即 0 或空字符串。我想用内联函数来做到这一点。到目前为止,我已经尝试了以下方法,但失败了。我做错了什么?
list_4 =[lambda i:list_3[list_2.index(list_1[i])] except "" for i in range(len(list_1))]
我的最终结果应该是这样的:
list_4=[0,5,4]
So, I have 3 lists as follows:
list_1 = ['a','b','c']
list_2 = ['b','c']
list_3 = [5,4]
I am looking to generate a fourth list of values from list_2 & list_3 that will map to list_1. list_2 and list_3 are independent of list_1 but are subsets of list_1 and do map to each other. i.e list_2 and list_3 is missing item 'a' and corresponding values.
I want to handle the missing values and assign some value i.e 0 or empty string. I would like to do this with an inline function. so far, I have tried the following but it fails. What am I doing wrong?
list_4 =[lambda i:list_3[list_2.index(list_1[i])] except "" for i in range(len(list_1))]
My final result should look like this:
list_4=[0,5,4]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不检查该值是否存在,而不是依赖异常处理?
Why don't you check for the presence of the value, instead of relying on exception handling?
一种更有效的方法来完成您想要的操作:
.get()
函数允许您指定默认值(如果未找到某些内容)。A more efficient way to do what you want:
.get()
function lets you specify a default value for if something isn't found.你不能像这样内联“ except”;它们仅成对出现在 try/ except 中,而这些不能在 lambda 中完成。
除非这是作业或谜题,否则我会使用字典:
zip 将两个列表组合成对:
dict 从中创建一个字典(关联数组):
和
.get(a ,b)
字典上的方法意味着“查找键 a 并返回该值,但如果未找到键,则返回 b”。You can't inline "except"s like that; they only come in try/except pairs, and those can't be done in a lambda.
Unless this is a homework assignment or a puzzle, I'd use a dictionary instead:
The zip combines the two lists into pairs:
The dict makes a dictionary (an associative array) out of this:
and the
.get(a,b)
method on a dictionary means "look up key a and return that valu, but if the key's not found, return b."根据您使用的 Python 版本,可能尚未包含 list.enumerate()。 enumerate 仍将作为内置函数存在,并将返回 (index, item) 的元组。所以您要寻找的行是:
Depending on what version of Python you're using, list.enumerate() might not be included yet. enumerate would still exist as a builtin, and would return tuples of (index, item). So the line you're looking for is: