[英]Comparing list values by index in Python
我需要查看列表中的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))
現在,您可以通過x in dic2 and y in dic2
使用x in dic2 and y in dic2
使用x in dic2 and y in dic2
並使用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
lis1=[1,2,3,4,5,6,7,8]
num1=lis1[1]
num2=lis1[4]
lis2=[11,12,13,14,2,7,5,34]
if num1 in lis2 and num2 in lis2:
if lis2.index(num1)>lis2.index(num2):
#do something here
else:
#do something else
如果我了解您要執行的操作,則可以采用以下方法:
score={}
Names = ["John", "James", "Barry", "Greg", "Jenny"]
Results1 = ["James", "Barry", "Jenny", "Greg", "John"]
Results2 = ["Barry", "Jenny", "Greg", "James", "John"]
r1dict={name:i for i,name in enumerate(Results1)}
r2dict={name:i for i,name in enumerate(Results2)}
for i, ni in enumerate(Names):
for j, nj in enumerate(Names):
if r1dict[ni] > r2dict[nj]:
score[(i,j)]=1
print(score)
打印:
{(0, 1): 1, (3, 2): 1, (4, 4): 1, (3, 3): 1, (2, 2): 1,
(4, 2): 1, (0, 3): 1, (0, 4): 1, (3, 4): 1, (0, 2): 1}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.