[英]Python create a list of X elements where the elements count by Y. For example, if X = 4 and Y = 5 you'd receive [5, 10, 15, 20]
[英]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.