简体   繁体   English

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

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

I have several lists that contain multiple sublists that are structured like this: 我有几个列表,其中包含多个子列表,其结构如下:

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

I have created a function that checks to see if a certain shape item is present and draws that shape. 我创建了一个函数来检查是否存在某个形状项目并绘制该形状。

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

This draws a dot at 0,0 when the function is entered like this: 像这样输入函数时,它将在0,0处绘制一个点:

draw_shape(shape_01)

I want to edit the function so it checks to see if 'Top' is present in the same sublist as the shape and then changes from drawing the dot at (0,0) to (0,100). 我想编辑该函数,以便它检查“ Top”是否在与形状相同的子列表中,然后从在(0,0)处绘制点变为(0,100)。

To sum up in the best terms I can state, how can I check if both 'Dot' and 'Top' are in the same sublist and have the code change accordingly? 总而言之,我可以陈述的最佳方式是,如何检查“ Dot”和“ Top”是否都在同一个子列表中,并相应地更改代码?

You could do it like this. 您可以这样做。 But it should be said that this approach doesn't really scale up if you want to add more attributes, shapes etc. 但是应该说,如果您想添加更多的属性,形状等,这种方法并没有真正扩大规模。

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)

To answer your specific question of how to check if the sublist contains multiple values, i recommend using a function, like this: 要回答有关如何检查子列表是否包含多个值的特定问题,我建议使用如下函数:

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)

It returns True if ALL values in values_to_find are present IN ANY sub_list of lists 如果values_to_find中的所有值都存在于列表的任何sub_list中,则返回True

so you can do: 因此,您可以执行以下操作:

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