在我的列表中找到副本,然后在代码中使用它

2024-09-28 05:26:15 发布

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

嗨,我正试图写一个代码,检查重复在我的名单。我想在以后的程序中使用这个副本(它用于一个谜题,其中有两个是谜题的正确答案)。 我希望“副本”存储在“I”中,这样我就可以执行以下操作 如果i=RGB_橙色-做这个或那个。只是一个例子

我试过很多不同的东西。这是我得到的最接近的。感谢您的帮助。
顺便说一句,该列表的内容是不同的RGB值。coordiantes是另一个列表,它是我的程序获取RGB值的地方

    for x in coordinates:
            rgbvalue = Tappair.getpixel(x)

#            rgblist = [(94, 197, 189), ## just an example
#                   (127, 176, 254),
#                   (233, 131, 78),
#                   (239, 106, 253),
#                   (233, 131, 78),
#                   (225, 81, 99),
#                   (126, 230, 129),
#                   (139, 33, 200)]

            rgblist = []


            rgblist.append(rgbvalue)
            print(rgblist)
            for i in rgblist:
                if rgblist.count(i) == 2:
                    print(i)
                    print("Counted")
                    print(rgblist)
                    break

编辑:这项工作:

def tap_the_pair():
if pyautogui.locateCenterOnScreen('TapPair.png', confidence=0.9, region=(689, 250, 640, 1000)) != None:
    Tappair = pyautogui.screenshot(region=(734, 429, 540, 540))
    Tappair.save(r"C:\Users\Andreas\Desktop\pythonProject\WholeTapPair.png")
    print("tap pair game found")

    rgblist = []

   # rgblist.append(rgbvalue)

    rgb_dict = {}

    for x in coordinates:
        rgbvalue = Tappair.getpixel(x)
        if rgbvalue in rgb_dict:
            print(rgbvalue)
            return rgbvalue
        else:
            rgb_dict[rgbvalue] = True

Tags: in程序列表forif副本rgbdict
2条回答

问题中提供的解决方案也有效,但其时间复杂度为O(n^2)。时间复杂度更好的方法是使用字典:

rgb_dict = {}

for rgb in rgblist:
    if rgb in rgb_dict:
        print(rgb)
        break
    else:
        rgb_dict[rgb] = True

循环结束后,rgb将包含重复项。此解决方案的时间复杂度为O(n)

编辑:尝试此代码特定于您的示例。它可以使用单个for循环来完成

rgb_dict = {}

for x in coordinates:
    rgbvalue = Tappair.getpixel(x)
    if rgbvalue in rgb_dict:
        print(rgbvalue)
        return rgbvalue
    else:
         rgb_dict[rgbvalue] = True

您可以通过以下方式在列表中找到重复项:

import collections

rgblist = [(94, 197, 189), (127, 176, 254), (233, 131, 78), (239, 106, 253), (233, 131, 78), (225, 81, 99), (126, 230, 129), (139, 33, 200)]

duplicates = [item for item, count in collections.Counter(rgblist).items() if count > 1]

print(duplicates)

for i in duplicates:
    # Do something with each duplicate

输出:

[(233, 131, 78)]     

相关问题 更多 >

    热门问题