簡體   English   中英

Python-將列表中的每個項目與列表中的其他所有項目進行比較

[英]Python - Comparing each item of a list to every other item in that list

我需要將很長的列表(12471個項目)中的每個項目與同一列表中的其他所有項目進行比較。 以下是我的清單:

[array([3, 4, 5])
array([ 6,  8, 10])
array([ 9, 12, 15])
array([12, 16, 20])
array([15, 20, 25])
...]                 #12471 items long

我需要將每個數組的第二項與其他每個數組的第一項進行比較,以查看它們是否相等。 並且優選地,以非常有效的方式。 在Python 2.x中有沒有一種簡單有效的方法來做到這一點?


我在這里設計了一種非常粗糙的方法,但是速度非常慢:

ls=len(myList)       #12471
l=ls
k=0
for i in myList:
        k+=1
        while l>=0:
            l-=1
            if i[1]==myList[l][0]:
                #Do stuff
        l=ls

雖然從理論上講這仍然是N ^ 2的時間(最壞的情況),但它應該會使情況變得更好:

import collections

inval = [[3, 4, 5],
[ 6,  8, 10],
[ 9, 12, 15],
[ 12, 14, 15],
[12, 16, 20],
[ 6,  6, 10],
[ 8,  8, 10],
[15, 20, 25]]

by_first = collections.defaultdict(list)
by_second = collections.defaultdict(list)

for item in inval:
    by_first[item[0]].append(item)
    by_second[item[1]].append(item)

for k, vals in by_first.items():
    if k in by_second:
        print "by first:", vals, "by second:", by_second[k]

我的簡單案例的輸出:

by first: [[6, 8, 10], [6, 6, 10]] by second: [[6, 6, 10]]
by first: [[8, 8, 10]] by second: [[6, 8, 10], [8, 8, 10]]
by first: [[12, 14, 15], [12, 16, 20]] by second: [[9, 12, 15]]

雖然這不處理重復項。

我們可以在O(N)中執行此操作,並假設python dict花費O(1)的時間進行插入和查找。

  1. 在第一次掃描中,我們通過掃描整個列表來創建一個存儲第一個數字和行索引的地圖
  2. 在第二次掃描中,我們發現第一次掃描中的map是否包含每行的第二個元素。 如果map包含,則map的值將為我們提供與所需條件匹配的行索引列表。
myList = [[3, 4, 5], [ 6,  8, 10], [ 9, 12, 15], [12, 16, 20], [15, 20, 25]]

    first_column = dict()
    for idx, list in enumerate(myList):
        if list[0] in first_column:
            first_column[list[0]].append(idx)
        else:
            first_column[list[0]] = [idx]

    for idx, list in enumerate(myList):
        if list[1] in first_column:
            print ('rows matching for element {} from row {} are {}'.format(list[1], idx,  first_column[list[1]]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM