Issue
I need to extract the most close element when counting backwards from a list of dicts based on a variable utime
. If utime
is less than uid.time
, it should not print anything.
I have created below script which does the work but doesn't seem to be efficient or foolproof as I have a preset value dif = 999999
. How to get rid of this and make this foolproof? Also if utime
is less than any of the uid.time
value, it should not print anything.
#!/usr/bin/python3
utime = 172200
uid = [
{
"id": 52,
"time": 172100
},
{
"id": 58,
"time": 172120
},
{
"id": 33,
"time": 172153
},
{
"id": 75,
"time": 172150
},
{
"id": 73,
"time": 172210
}
]
dif = 999999
ind = 0
for indx,i in enumerate(uid):
tDiff = utime - i['time']
if (tDiff > 0 and tDiff < dif):
dif = tDiff
ind = indx
print(uid[ind])
Expected Output (which I am getting anyway)
{'id': 33, 'time': 172153}
Solution
You can call min
on the list with a key function that returns a tuple of whether or not the diff is non-positive, and the diff itself:
min(uid, key=lambda d: ((diff := utime - d['time']) <= 0, diff))
Demo: https://ideone.com/gDKJ6A
EDIT: If you want to avoid printing anything when therer is no entry in uid
whose time
is less than utime
, you can use a generator expression to filter out unwanted entries before calling min
with a default value of None
:
if closest := min(
((diff, d) for d in uid if (diff := utime - d['time']) > 0),
default=None
):
print(closest[1])
Demo: https://ideone.com/4xAPJf
Answered By - blhsing
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.