将值与lis进行比较

2024-05-12 20:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理我的代码,因为我正在计算的按钮宽度和像素加在一起得到的价值。我试图在计算时将值与列表进行比较,以查看值是否接近、更高或等于。你知道吗

代码如下:

CurrentRows = [375, 441, 507, 559, 610, 669, 724, 790, 838, 844, 849, 897, 910, 949, 959, 1009, 1016, 1018, 1019, 1072, 1125, 1138, 1184, 1186, 1189, 1238, 1246, 1286, 1419, 1620, 1762, 1840, 1943]

nextprogram = int(program_id) + 1
nextprogram1 = int(nextprogram) + 1
nextprogram2 = int(nextprogram1) + 1
nextprogram3 = int(nextprogram2) + 1
program_button_1 = self.getControl(int(program_id))
program_button_2 = self.getControl(int(nextprogram))
program_button_3 = self.getControl(int(nextprogram1))
program_button_4 = self.getControl(int(nextprogram2))

width = program_button_1.getWidth()
pos_X = pos_X + width + 5

for pos_X1 in CurrentRows:
   if pos_X1 >= pos_X:
      pos_X = pos_X1
      break

program_button_2.setPosition(pos_X, pos_Y)
width = program_button_2.getWidth()
pos_X = pos_X + width + 5

for pos_X1 in CurrentRows:
    if pos_X1 >= pos_X:
       pos_X = pos_X1
       break

program_button_3.setPosition(pos_X, pos_Y)
width = program_button_3.getWidth()
pos_X = pos_X + width + 5


for pos_X1 in CurrentRows:
    if pos_X1 >= pos_X:
       pos_X = pos_X1
       break

当变量pos_X显示接近1184的值1194时,我想从列表中得到1184的值。当值show 1083时,我想从列表中获取1073,但当值show 1125与列表匹配时,我想从列表中获取1125。你知道吗

我怎么能用我的代码做到这一点?你知道吗


Tags: 代码posself列表buttonprogramwidthint
1条回答
网友
1楼 · 发布于 2024-05-12 20:36:24

有几种方法可以做到这一点,我只是列举了一些。第一个问题是我最喜欢的方法是什么,但这可能不是最有效的方法,如果这正是你所担心的:

def highest(maximum):
    return max([row for row in CurrentRows if row <= maximum])

下一个也使用max,但应该只需要对行列表进行一次传递。你知道吗

def highest(maximum):
    return max(CurrentRows, key=lambda x: x if x <= maximum else 0)

如果出于任何原因你不喜欢max,你总是可以迭代列表并自己检查。你知道吗

def highest(maximum):
    best = 0
    for x in CurrentRows:
        if x > maximum:
            return best
        best = x
    return best

相关问题 更多 >