2

リストの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チュートリアルを見てきましたが、私の質問に答えるものは何もないようです。

4

3 に答える 3

3

list2アイテムを指定した位置をエンコードする辞書に変換します。

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

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
于 2012-07-10T22:24:21.590 に答える
2
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
于 2012-07-10T22:16:23.683 に答える
1

あなたがやろうとしていることを私が理解しているなら、ここにアプローチがあります:

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}
于 2012-07-10T22:53:27.490 に答える