简体   繁体   English

列表推导中的海象运算符(python)

[英]Walrus operator in list comprehensions (python)

So when coding I really like to use list comprehensions to transform data and I try to avoid for loops.因此,在编码时,我真的很喜欢使用列表推导来转换数据,并且我尽量避免 for 循环。 Now I discovered that the walrus operator can be really handy for this, but when I try to use it in my code it doesn't seem to work.现在我发现海象运算符可以非常方便地完成此操作,但是当我尝试在我的代码中使用它时,它似乎不起作用。 I've got the following code and want to transform the strings containing data about the timestamps into datetime objects in one easy line, but I get an syntax error and I am not sure what the right syntax would be, does anyone know what I did wrong?我有以下代码,想在一个简单的行中将包含有关时间戳的数据的字符串转换为 datetime 对象,但出现语法错误,我不确定正确的语法是什么,有人知道我做了什么错误的?

from datetime import datetime

timestamps = ['30:02:17:36',
              '26:07:44:25','25:19:30:38','25:07:40:47','24:18:29:05','24:06:13:15','23:17:36:39',
              '23:00:14:52','22:07:04:33','21:15:42:20','21:04:27:53',
              '20:12:09:22','19:21:46:25']

timestamps_dt = [
    datetime(days=day,hours=hour,minutes=mins,seconds=sec) 
    for i in timestamps
    day,hour,mins,sec := i.split(':')
] 

Since Walrus operator does not support values unpacking, the operation由于 Walrus 算子不支持值解包,因此该操作

day,hour,mins,sec:= i.split(':')

is invalid.是无效的。

Walrus operator is recommended to be used mostly in logic comparison, especially when you need to reuse a variable in comparison.海象算子推荐多用于逻辑比较,特别是当你需要重用一个变量进行比较时。 Therefore, I would argue that for this case, a simple datetime.strptime() would be better for this case.因此,我认为对于这种情况,简单的datetime.strptime()会更好。

If you must use walrus comparison in your list comprehension, you may do如果您必须在列表理解中使用海象比较,您可以这样做

from datetime import datetime

timestamps = ['30:02:17:36',
              '26:07:44:25','25:19:30:38','25:07:40:47','24:18:29:05','24:06:13:15','23:17:36:39',
              '23:00:14:52','22:07:04:33','21:15:42:20','21:04:27:53',
              '20:12:09:22','19:21:46:25']

timestamps_dt = [
    datetime(2020,11, *map(int, time)) # map them from str to int
    for i in timestamps
    if (time := i.split(':')) # assign the list to the variable time
]
print(timestamps_dt)

But then it will lead to a question why not just,但这会导致一个问题,为什么不只是,

timestamps_dt = [
    datetime(2020,11, *map(int, i.split(':'))) 
    for i in timestamps
]

Reference PEP-572参考PEP-572

...and want to transform the strings containing data about the timestamps into datetime objects in one easy line, ...并希望在一行中将包含有关时间戳的数据的字符串转换为 datetime 对象,

If you want to convert the list of strings into a list of datetime objects you can use the below one liner:如果要将字符串列表转换为日期时间对象列表,可以使用以下一个衬里:

timestamps_dt = [datetime.strptime(d, '%d:%H:%M:%S') for d in timestamps]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM