簡體   English   中英

如何在兩個列表中搜索該對?

[英]How to search for the pair in two lists?

我有兩個主要列表,每個列表包含 10 個字符串:

bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']

這些列表基本上包含方向的可能組合,所以基本上,出現在bus0中第 0 個 position 的元素將在bus1中的相同位置(第 0 個)具有可能的對,最重要的是組合是唯一的,例如,除了0th position position 之外,您不會在任何其他 position 找到North-EastEast-North 我有另一個包含 10 個數字的列表。

data = [12, 23, 34, 45,13, 133, 324, 475,94,66]

現在有兩個對列表,它基本上告訴我們需要在bus0bus1中搜索哪對。

pair1 = ['north', 'north', 'south']
pair2 = ['northeast', 'west', 'east']

所以從技術上講,會有三對:

  1. 東北偏北(第三位)
  2. 西北(第一名)
  3. 東南(第五位)

現在要從data列表中獲取數據,我只需要從這些位置中選擇元素。 我的方法:

bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']
data = [12, 23, 34, 45,13, 133, 324, 475,94,66]

bus0 = [i.lower() for i in bus0]
bus1 = [i.lower() for i in bus1]
combine = [(i,j,k) for i,j,k in zip(bus0, bus1, data)]


pair1 = ['north', 'north', 'south']
pair2 = ['northeast', 'west', 'east']

for i  in combine:
    for k,l in zip(pair1, pair2):
        if i[0]==k and i[1]==l:
            print(i[0]+'-'+ k)
            print(i[0] + '-' + l)
            print(i[2])

誰能幫忙?

您可以創建一個字典,其中鍵是兩個列表的排序值,然后創建兩個對列表的排序值並查找值。

bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']
data = [12, 23, 34, 45,13, 133, 324, 475,94,66]

pair1 = ['north', 'north', 'south']
pair2 = ['northeast', 'west', 'east']


pairs = ['-'.join(sorted([x.lower(), y.lower()])) for x,y in zip(pair1,pair2)]
m = dict(zip(['-'.join(sorted([x.lower(),y.lower()])) for x,y in zip(bus0,bus1)],data))

[m[x] for x in pairs]

Output

[45, 23, 133]

暫無
暫無

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

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