在python中构造从大到小的整数列表

2024-10-04 01:37:33 发布

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

我正在尝试开发一个小鼠标控制器应用程序。它应该得到(X,Y)坐标并使光标移到那里。在

问题是,当它试图转到比当前坐标小的X坐标时。在

import win32con
from win32api import GetCursorPos, SetCursorPos, mouse_event, GetSystemMetrics
from time import sleep

def clickWithCursor(xDesired, yDesired):
    xCurrent, yCurrent = GetCursorPos()

slope = float(yDesired - yCurrent) / float(xDesired - xCurrent)

def goAhead(x, y):
    for x in range(min(xCurrent, xDesired), max(xDesired, xCurrent), 2):
        y = int(slope * (x - xCurrent) + yCurrent)
        SetCursorPos((int(x), y))
        sleep(0.002)

    mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

return goAhead(0, 0)

def main():
    clickWithCursor(243, 184)

main()

以上只是一个非常糟糕的尝试,没有给我的结果,我正在寻找。我到处找怎么做,就是找不到正确的方法。在

简而言之,我想构造一个列表,这样它就可以根据参数的顺序从大到小,或者从小到大

所以,如果我给出范围(4,1)我想要得到的结果是:[4,3,2]或者范围(1,4),它不会介意并以正确的方式构造它。。。在

编辑: 我根据答案重构了代码,让其他用户更容易阅读。注意MouseController类中的“sequence”方法:

^{pr2}$

Tags: fromimporteventdefsleepslopemousewin32con
3条回答

在获得最小值和最大值后,根据哪个值更大,执行-1或1步:

def up_down(a, b):
    mn, mx = min(a), max(b)
    step = -1 if mn > mx else 1
    return range(mn, mx, step)

输出:

^{pr2}$

如果最小值更大,我们需要一个负的步长,如果不是只使用1的步长。在

要使如何在自己的代码中使用逻辑变得更加明显,只需使用if/else:

def goAhead(x, y,n=1):
    step = -n if xCurrent > xDesired else n
    for x in range(xCurrent, xDesired, step):
        y = int(slope * (x - xCurrent) + yCurrent)
        SetCursorPos((int(x), y))
        sleep(0.002)

如果您想更改步长,您可以传递任何您想要的n

range(a, b, -1 if a > b else 1)

lim1, lim2 = 10, 2  
step = 1 if lim1<lim2 else -1  
lst = list(range(lim1, lim2, step))  
print(lst)  

=>;[10,9,8,7,6,5,4,3]

使用:
lim1,lim2=2,10

=>;[2,3,4,5,6,7,8,9]

此表单允许:
列表(范围(lim1,lim2,如果lim1,则为1 在

相关问题 更多 >