3 ms·
The first example can be written like this in Python >= 3.8: a = 1 b = 2 ((a := a + 1) if a == b else (b := b + 1)) + 1 although that's a lot to c
by saila 4y ago
The first example can be written like this in Python >= 3.8:
a = 1
b = 2
((a := a + 1) if a == b else (b := b + 1)) + 1
although that's a lot to cram into a single line IMO.
The closest I could come up with for the second example is this (noting that the datetime constructor requires both the year and month):
from datetime import datetime
timestamps = [
"2022:04:30:02:17:36",
"2022:04:26:07:44:25",
"2022:04:25:19:30:38",
"2022:04:25:07:40:47",
]
datetimes = [
datetime(*map(int, timestamp.split(":")))
for timestamp in timestamps
]
That said, it'd probably be better to use datetime.fromisoformat() or datetime.strptime() rather than manual parsing.
And you could maybe use the operator module[1] for the last example, like this:
import operator as op
(op.add if 1 < 0 else op.mul)(42, 100)
[1] https://docs.python.org/3/library/operator.html https://docs.python.org/3/library/operator.html
- chrismorgan 4y agoThere’s a rather important semantic difference in what you wrote: a++ produces the value before incrementing, whereas (a := a + 1) is like ++a and produces the value after incrementing. Presuming this is indeed what behnamoh meant by a++, that `(a++ if a==b else b++) + 1` would be better written `++a if a==b else ++b`, which would then become the clearer `(a := a + 1) if a == b else (b := b + 1)`.