簡體   English   中英

Python 3:如何檢查列表中的項目是否在列表中並打印

[英]Python 3: How to check if the item from list is in list and print it

我有一個列表列表,其中包含坐標

points = [[5821, 293], [3214, 872], [4218, 820], [1223, 90], [7438, 820]]

我需要找到一對具有相同point [i] [1]的列表 ,然后將它們都打印出來。 僅給出此坐標。 在代碼中,它們是隨機分配的。 這個怎么做?

您可以使用itertools.combinations在每兩個項目之間創建一系列對,並僅過濾出具有相同第二個項目的對:

from itertools import combinations
result = [x for x in combinations(points, 2) if x[0][1] == x[1][1]]

不確定我是否正確理解了問題,但這是我的方法。

順便說一下,我使用python 3.5.2

如果您打算使用[1]或y坐標(取決於您的查看方式)來捕獲所有列表,且這些列表的值為820,則代碼可以是:

for i in points:
    if i[1] == 820:
        print(i)

沒有簡單有效的方法可以對當前數據結構進行所需的操作。

您可以使用效率低的方法( O(N**2) ),也可以將數據轉換為可以使用更高效算法的另一種格式。

Mureinik的答案是進行O(N**2)搜索的好方法,因此,我將提供一個使用字典的解決方案來快速進行檢查:

def find_matches(points):
    dct = {}
    for x, y in points:
        for other_x in dct.setdefault(y, []):
            yield (x, y), (other_x, y)
        dct[y].append(x)

這是一個發生器,這將yield對點的具有匹配y值。 它應該使用O(N)空間和O(N+R)時間(用於N輸入點和R對匹配項)。

這是適合您的代碼:

 second_list = [] 
 the_list = [[5821, 293], [3214, 872], [4218, 820], [1223, 90], 
 [7438, 820]]
 for i in the_list:
      second_list.append(i[1])

 repeated = []
 the_new_list = sorted(second_list, key=int)
 for i in range(len(the_new_list)):
     if i + 1 < len(the_new_list):
          if the_new_list[i] == the_new_list[i+1]:
               repeated.append(the_new_list[i])

 for i in the_list:
      if i[1] in repeated:
          print(i)

second_list存儲列表的y坐標。 然后,程序按升序對y坐標列表進行排序,並將其附加到the_new_list。 最后,我們遍歷the_new_list,看看彼此之后的數字是否相等,如果相等,則將它們重復添加到列表中。 然后,我們遍歷the_list,看看是否有重復的點。 如果是這樣,我們將打印整個內容。 希望對您有所幫助。

暫無
暫無

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

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