簡體   English   中英

Python 如何在列表 X 中搜索元素 Y。元素 Y 是一個列表本身,其元素可能與 X 中列出的順序不符

[英]Python How to search through list X for element Y. Element Y is a list itself whose elements may not be in order as listed in X

我有一個清單:

X = ['rgb','rg870','rg1200','rg1550']

我的第二個清單是:

Y = [870,r,g]

我想在X列表中搜索Y列表的組合,即使訂單不匹配並返回元素索引。

這應該返回索引 1。#至少我認為它的位置 1 作為第一個元素是 0?

嘗試這個:

import numpy as np

X = ['rgb','rg870','rg1200','rg1550']

Y = ['870','r','g']

result = np.where([sorted(''.join(Y))==sorted(x) for x in X])[0]
print(result)

代碼說明:

  • ''.join(Y)使您從列表Y移動到所有元素以空字符分隔的字符串。
  • sorted(''.join(Y))對新創建的字符串sorted(''.join(Y))
  • sorted(x)以相同的方式sorted(x) x ,它是X列表推導式迭代的一個元素。
  • 通過比較排序后的字符串,您可以確保Y所有字符都以相同的數字包含在元素x中,即使原始順序不同。
  • 使用np.where(_)搜索匹配發生的位置。 由於通常np.where用於矩陣,您只需要選擇第一個元素: np.where(_)[0]
  • 最后打印結果,這是匹配發生的位置列表。 如果您確定只發生一個匹配項,那么您可以簡單地執行result = np.where(_)[0][0]提取它,從而獲取結果列表的元素 0。
# I have a list: 
X = ['rgb','rg870','rg1200','rg1550']

# My second list is: 
Y = ['870','r','g']

# I want to search in the X list and for the combination
# of Y list even if the order doesn't match and return the element index.

# This should return index of 1. #At lest I think its 
# position 1 as the first element is 0?
# You don't mind if I use more descriptive variable names?

def find_combo(full_ids,segments):
  for idx,full_id in enumerate(full_ids):
    is_match = True
    for segment in segments:
      if segment in full_id:
        pass
      else:
        is_match = False
        break
    if is_match:
      return idx
    else:
      continue
    
find_combo(X,Y)
>>> 1

暫無
暫無

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

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