gpt4 book ai didi

python - 如何在不损失效率的情况下将这段代码变成 1 行?

转载 作者:太空宇宙 更新时间:2023-11-04 00:01:01 25 4
gpt4 key购买 nike

为了提高可读性,我想把这段代码变成 1-liner。

变量 tup_ranges 是一个包含 2 个值的元组,例如(20, 40)。如果 elt 的值包含在此范围内,则检索与此值 n 对应的键。

identification = dict()
for elt in combination:
for n, tup_range in ranges.items():
if tup_range[0] <= elt and elt <= tup_range[1]:
identification[elt] = n

不知怎么的,这段代码我想不出好的写法...

identification = {elt: [n for n, tup_range in ranges.items() if tup_range[0] <= elt and 
elt <= tup_range[1]][0] for elt in combination}

工作但由于中间创建的列表而变慢......无论如何要摆脱这个只有一个元素的列表?

尝试一下:

ranges = {25: (20, 32), 35: (33, 45)}
combination = (30, 30, 40)
# Output:
{30: 25, 40: 35}

P.S:确实这个问题会在代码审查中占有一席之地,但我觉得这主要是字典理解的错误设计。

最佳答案

您的一行代码的可读性更高的版本可能是

identification = {elt: n for n, tup_range in ranges.items() for elt in combination if tup_range[0] <= elt <= tup_range[1] }
#{30: 25, 40: 35}

或者

identification = {elt: n for n in ranges for elt in combination if ranges[n][0] <= elt <= ranges[n][1] }

只是尝试对这两种方法进行计时

ranges = {25: (20, 32), 35: (33, 45)}
combination = (30, 30, 40)
identification = {}
import time
start = time.time()
for elt in combination:
for n, tup_range in ranges.items():
if tup_range[0] <= elt and elt <= tup_range[1]:
identification[elt] = n
end = time.time()
print(end-start)
#1.2159347534179688e-05
ranges = {25: (20, 32), 35: (33, 45)}
combination = (30, 30, 40)
identification = {}
import time
start = time.time()
identification = {elt: n for n in ranges for elt in combination if ranges[n][0] <= elt <= ranges[n][1] }
end = time.time()
print(end-start)
#5.0067901611328125e-06

字典理解速度快 10 倍

关于python - 如何在不损失效率的情况下将这段代码变成 1 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com