[英]Improve code readability of a Python lambda expression with condition
First of all I do not know if these types of questions are appropriate in stackoverflow.首先,我不知道这些类型的问题是否适用于 stackoverflow。
I have the following dict:我有以下字典:
file_dict = {"asda_20221003:ada":1, "scdfws_20221104eaf2we":5, "iasndcfiopsadn":9}
The key values of the dict always contains a date with the format %Y%m%d, what i want i to obtain the value for the key that have the highest date. dict 的键值始终包含格式为 %Y%m%d 的日期,我希望我获得具有最高日期的键的值。
What I have done is the following:我所做的如下:
OrderedDict(sorted(file_dict.items(), key=lambda t: datetime.strptime(re.findall("\d{8}",t[0])[0], "%Y%m%d") if len(re.findall("\d{8}",t[0])) > 0 else datetime.min, reverse=True))
This expression works but it is unreadable.此表达式有效,但不可读。 Is there any way in order to improve it?
有什么办法可以改善吗?
what i would like is to asigne at some point re.findall("\d{8}",t[0])
to a variable (for example date) and use this one for all the expression.我想要的是在某个时候
re.findall("\d{8}",t[0])
分配给一个变量(例如日期),并将其用于所有表达式。
Something like this:像这样:
OrderedDict(sorted(file_dict.items(), key=lambda t: datetime.strptime(x[0], "%Y%m%d") if len(re.findall("\d{8}",t[0]) as x) > 0 else None, reverse=True))
I am also open for other ways to perform this operation我也愿意使用其他方式来执行此操作
You can simply compare list of strings and not compare datetimes.您可以简单地比较字符串列表而不比较日期时间。
As @Steven Rumbalski said: Note that as of Python 3.7 dictionaries are guaranteed to retain the insertion order of the keys, so OrderedDict()
can be replaced by dict()
in this example.正如@Steven Rumbalski 所说:请注意,从 Python 开始,3.7 字典保证保留键的插入顺序,因此在此示例中
OrderedDict()
可以替换为dict()
。
OrderedDict(
sorted(file_dict.items(),
key=lambda t: re.findall(r"\d{8}", t[0]),
reverse=True))
# OR
dict(
sorted(file_dict.items(),
key=lambda t: re.findall(r"\d{8}", t[0]),
reverse=True))
Results:结果:
OrderedDict([('scdfws_20221104eaf2we', 5),
('asda_20221003:ada', 1),
('iasndcfiopsadn', 9)])
# OR
{'scdfws_20221104eaf2we': 5, 'asda_20221003:ada': 1, 'iasndcfiopsadn': 9}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.