gpt4 book ai didi

python - 在 Python 中按索引比较列表值

转载 作者:行者123 更新时间:2023-11-28 21:27:15 25 4
gpt4 key购买 nike

我需要查看一个列表中的 2 个项目是否出现在另一个列表中,如果出现,则根据项目在另一个列表中的位置进行比较。伪代码示例:

j=0
for x in mylist #loop through the list
i=0
for y in mylist #loop through the list again to compare items
if index of mylist[j] > index of mylist[i] in list1 and list2:
score[i][j] = 1 #writes the score to a 2d array(numpy) called score
i=i+1
else:
score[i][j]=0
i=i+1
j=j+1

样本叙述描述:

Names = [John, James, Barry, Greg, Jenny]
Results1 = [James, Barry, Jenny, Greg, John]
Results2 = [Barry, Jenny, Greg, James, John]

loop through Names for i
loop through Names for j
if (index value for john) > (index value for james) in results1 and
(index value for john) > (index value for james) results2:
score[i][j] = 1

有人可以指出我正确的方向吗?我一直在查看大量列表、数组和 .index 教程,但似乎没有任何内容可以回答我的问题

最佳答案

将您的 list2 转换为对给定项目的位置进行编码的字典:

dic2 = dict((item,i) for i,item in enumerate(list2))

现在您可以使用 dic2 中的 x 和 dic2 中的 y 测试列表中的内容,并使用 dic2[x] 获取它在列表中的索引。

编辑:这违背了我更好的直觉,但这是完整的代码。第一部分是使用我上面展示的内容,将一个简单列表转换为索引查找。接下来是标准的初始化 2D 列表的方式,虽然这种方式不直观。接下来是您的循环,使用非常方便的 enumerate 函数为列表中的每个名称分配索引。

Names = ['John', 'James', 'Barry', 'Greg', 'Jenny']
Results1 = ['James', 'Barry', 'Jenny', 'Greg', 'John']
Results2 = ['Barry', 'Jenny', 'Greg', 'James', 'John']

Order1 = dict((name,order) for order,name in enumerate(Results1))
Order2 = dict((name,order) for order,name in enumerate(Results2))

score = [[0]*len(Names) for y in range(len(Names))]

for i,name1 in enumerate(Names):
for j,name2 in enumerate(Names):
if name1 in Order1 and name2 in Order1 and Order1[name1] > Order1[name2] and name1 in Order2 and name2 in Order2 and Order2[name1] > Order2[name2]:
score[i][j] = 1

关于python - 在 Python 中按索引比较列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11422781/

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