簡體   English   中英

查找列表的子列表中是否存在某項之后,請查找同一子列表中是否存在另一項

[英]After finding if an item is present in a sublist of a list, find if another item is in the same sublist

我有幾個列表,其中包含多個子列表,其結構如下:

shape_01 = [['Circle', 'Top'], ['Dot', 'Top']]

我創建了一個函數來檢查是否存在某個形狀項目並繪制該形狀。

def draw_shape(set):
     if any(('Dot') in i for i in set):
     goto(0,0)  
     dot(25)

像這樣輸入函數時,它將在0,0處繪制一個點:

draw_shape(shape_01)

我想編輯該函數,以便它檢查“ Top”是否在與形狀相同的子列表中,然后從在(0,0)處繪制點變為(0,100)。

總而言之,我可以陳述的最佳方式是,如何檢查“ Dot”和“ Top”是否都在同一個子列表中,並相應地更改代碼?

您可以這樣做。 但是應該說,如果您想添加更多的屬性,形狀等,這種方法並沒有真正擴大規模。

def goto(*pos): print(pos)
def dot(*params): print(params)

def draw_shape(lst):
    for l in lst:
        if 'Dot' in l:
            if 'Top' in l:
                goto(100, 0)
            else:
                goto(0,0)
            dot(25)

def draw_shape(lst):
    for l in lst:
        if 'Dot' in l and 'Top' in l:
            goto(100, 0)
            dot(25)
        elif 'Dot' in l:
            goto(0,0)
            dot(25)

要回答有關如何檢查子列表是否包含多個值的特定問題,我建議使用如下函數:

def any_sublist_contains_all(lists, values_to_find):
    return any(all(value in l for value in values_to_find) for l in lists)

如果values_to_find中的所有值都存在於列表的任何sub_list中,則返回True

因此,您可以執行以下操作:

if any_sublist_contains_all(set, ('Dot','Top')):
    # dot what you want

您可以利用python中的集合。

set(sublist).issuperset(['Top', 'Dot'])

暫無
暫無

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

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