[英]What's the neatest way to get a value from a dictionary and convert to an integer if it exists – in python 3.8?
I'm looking for a neater way to retrieve a value from a dictionary (if it exists) and convert to an integer (or replace with 0) using python 3.8.我正在寻找一种更简洁的方法来从字典中检索值(如果存在)并使用 python 3.8 转换为 integer(或替换为 0)。
Here's the code I'm using now:这是我现在使用的代码:
import re
data = {"x":"10", "y":"blank"}
for key in data.keys():
n = data.get(key,0)
n = int(n) if re.search("[0-9]+", n) else 0
print(n)
I'd like to condense the int
conversion into one line – possibly without regex?我想将
int
转换压缩成一行——可能没有正则表达式? Is that possible?那可能吗? Or perhaps using a pipe feature to move the logic to to the same line?
或者也许使用 pipe 功能将逻辑移动到同一行?
You can do it in one line without regex like this:您可以在没有正则表达式的情况下在一行中完成,如下所示:
data = {k: int(n) if n.isnumeric() else 0 for k, n in data.items()}
You can use comprehension to get it all in one line您可以使用理解将所有内容集中在一行中
import re
data = {"x":"10", "y":"blank"}
data = {k:int(v) if re.search("^[0-9]+$", v) else 0 for k, v in data.items()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.