如何比较两个不同大小的列表,找到匹配项和 return 两个列表中这些匹配项的索引

How do I compare two lists of diffrent sizes, find matches and return the indices of those matches in both lists

在 pygame 我正在构建 GA 模拟。模拟涉及10个生物和100块食物。我正在将它们创建为精灵。我尝试使用内置的精灵碰撞检测,但我需要检测独特精灵之间的碰撞,而不是精灵与组或组与组之间的碰撞。这让我意识到我需要一个定制的解决方案。由于我的数字很低,我想我可以将食物和生物的位置放入列表中并进行比较。该部分有效,但我无法弄清楚的是如何获取列表中匹配项的索引。我不太担心速度,因为我认为我的比较速度足够快,尤其是考虑到所涉及的数据量小且碰撞相对罕见,但我仍然想要一种廉价的解决方案来找到这些索引。我可以创建字典等。我不确定什么是最好的方法。我的比较测试代码如下,运行良好,给出了一半的答案,即发生碰撞的机器人的索引。我现在只需要碰撞的食物的索引。

from random import *
food = [(randint(0, 1000), randint(0, 1000)) for i in range(100)]
while True:
    bots = [(randint(0, 1000), randint(0, 1000)) for i in range(10)]
    for i in range(len(bots)):
        if bots[i] in food:
            print(i, bots[i])
    for i in range(len(food)):
        if food[i] in bots:
            print(i, food[i])

上面的代码正是我想要的,但是是一个肮脏的障碍,而且非常昂贵。它让我现在继续前进,但必须对其进行改进。

很难给出具体的答案,因为我不知道什么是GA模拟。遗传算法?是 2d、3d 还是 nd?他们中任何一个的方法都是相似的。

最好以不同的方式处理这个问题。

我们有一个“位置”,其中包含:它的标识符,即 x,y(,z...) 坐标,机器人存在的值,以及食物存在的值。然后主要数据结构是所有这些位置的列表。

现在,对于每一帧 (step/generation/etc),我们迭代所有可能的位置,如果任何位置的食物和机器人的值都存在,我们就知道发生了碰撞。从那里开始,它只是为您的 sim 集成您想要的任何逻辑。

对于食物,使用字典而不是列表....

from random import randint

food = {i:(randint(0, 1000), randint(0, 1000)) for i in range(100)}
while True:
    
    bots = [(randint(0, 1000), randint(0, 1000)) for i in range(10)]
    for i in range(len(bots)):
        if bots[i] in food.values():
            
            print(f'Bot num {i} collided with food num {list(food.keys())[list(food.values()).index(bots[i])]}')
            # "list(food.keys())[list(food.values()).index(bots[i])]" finds the key of the given value (here, the bot position)

输出:

Bot num 3 collided with food num 80
Bot num 6 collided with food num 51
Bot num 3 collided with food num 32
Bot num 8 collided with food num 86
Bot num 7 collided with food num 98
Bot num 9 collided with food num 94
Bot num 5 collided with food num 88

这一直持续到我停止。