簡體   English   中英

Python - 搜索包含一個元素的列表中的列表索引

[英]Python - Searching index of lists in list containing one element

我有一個4長列表的列表L.

L = [[1,2,12,13],[2,3,13,14],...]

和兩個整數a和b,在子列表中出現多次。 我想要的是找到L中包含AND b的子列表的索引。

我寫了一些代碼

l=[]
for i in range(len(L)):
    if L[i][0]==a or L[i][1]==a or L[i][2]==a or L[i][3]==a:
        l.append([i] + L[i]) # I put the index in the first position.
# Now l is a list of 5-length lists.
# I do the same loop on that list.
r=[]
for i in range(len(l)):
    if l[i][1]==b or l[i][2]==b or l[i][3]==b or l[i][4]==b:
        r.append(i)

我正在尋找的索引在列表r中。 但是我很確定在Python中有另一種方法可以做到這一點,因為我幾乎不懂這種語言。 也許如果我的變量L不是列表列表,那么它會更容易/更快,因為我會在我的主程序中調用這個過程。 (len(L)約為3000)

順便說一句,我知道索引的數量在1到4之間,所以我可以放一些休息,但我不知道它是否會更快。

----------------編輯1 ----------------

在第二句中將“a或b(或包含)”改為“a AND b”。 我寫了一個關於我的目標的錯誤。

你可以這樣做:

r = [i for i,x in enumerate(L) if any(y in x for y in (a,b))]

枚舉將在列表推導中為您提供索引和值,any語句將告訴您a或b是否在x中,這是L中的子列表

使用any()測試子列表:

if any(a in subl for subl in L):

這將測試每個subl但如果找到匹配,則提前退出生成器表達式循環。

,但是,返回匹配特定的子表。 您可以使用帶有生成器表達式的next()來查找第一個匹配項:

matched = next((subl for subl in L if a in subl), None)
if matched is not None:
    matched[1] += 1

如果生成器表達式引發StopIteration異常,則返回None是缺省值,或者可以省略缺省值並使用異常處理:

try:
    matched = next(subl for subl in L if a in subl)
    matched[1] += 1
except StopIteration:
    pass # no match found

這種事情是列表理解的內容。

如果你真的想要包容性或 - 那么這就是你想要的清單。 在您的代碼中,您目前正在給予和。

result = [a_tuple for a_tuple in L if a in a_tuple or b in a_tuple]

試試吧

for index, item in enumerate(L):
  if a in item or b in item:
    r.append(index)

暫無
暫無

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

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