检查python列表中是否有预定义的匹配项

时间:2018-07-13 09:20:31

标签: python-3.x list pattern-matching

我是Python初学者,我想知道是否有人可以建议我如何检查预定义对数的列表。

green = yellow and blue 
purple = blue and red 
orange = red and yellow 
grey = white and black 
beige = white and yellow 
brown = black and yellow 

这些是许多示例列表,我想对其进行遍历并检查其中是否存在上述任何对。如果它们确实存在于列表中,那么我想返回该对的名称。

Lists: 
List1 ['white','black','yellow'] (return: brown, beige)
List2 ['yellow','white','black','red'](return: beige, grey, orange)
List3 ['blue','yellow','red'] (return: green, purple)
List4 ['white','red','blue'] (return: purple)

我尝试按列表的长度过滤列表,然后检查到目前为止每个元素的成员资格,但它不会返回所有可能的对。

谢谢您的帮助!

以下是我到目前为止尝试过的事情: (1)遍历每个列表并为每个项目进行测试(但这不会返回所有可能的解决方案)

if "white" and "yellow" in list1:
    result = 'beige'

elif 'yellow' and 'black' in list1:
    result = 'brown'

else: 
result = 'None'

(2)

len_of_list = len(lists) 
if len_of_list == 3:
three = lists
for item in three:
        if any (colour in three for colour in ('yellow','black')):
            print(three)

(3)

if len_of_list ==3: 
    three = lists
    first_el = three[0]
    second_el = three[1]
    last_el = three[-1]

if "yellow" in first_el and "black" in second_el:
           result = 'brown'

elif 'yellow' in first_el and 'black' in last_el:
    result = 'brown'

elif 'yellow' in second_el and 'black' in last_el:
    result = 'brown'

1 个答案:

答案 0 :(得分:0)

此函数使用辅助颜色及其组成颜色的字典,并检查组成颜色的集合是否是传递给它的颜色集合的子集:

secondary_colours = {"green": ("yellow", "blue"),
                     "purple": ("blue", "red"),
                     "orange": ("red", "yellow"),
                     "grey": ("white", "black"),
                     "beige": ("white", "yellow"),
                     "brown": ("black", "yellow")}

def obtainable_colours(primary_colours):
    """Returns a list of secondary colours obtainable
    from combinations of the primary colours provided.
    Assumes additive pigment mixing as defined above."""
    global secondary_colours
    response = []
    for s_col,components in secondary_colours.items():
        if set(components) < set(primary_colours):
            response.append(s_col)
    return response

测试:

p1 = ['white','black','yellow'] 
p2 = ['yellow','white','black','red']
p3 = ['blue','yellow','red'] 
p4 = ['white','red','blue']

for p in [p1,p2,p3,p4]:
    print(p)
    print(obtainable_colours(p))
    print("\n")

>>>

['white', 'black', 'yellow']
['grey', 'beige', 'brown']


['yellow', 'white', 'black', 'red']
['orange', 'grey', 'beige', 'brown']


['blue', 'yellow', 'red']
['green', 'purple', 'orange']


['white', 'red', 'blue']
['purple']