首页 > 解决方案 > 检查 python 列表中的预定义匹配项

问题描述

我是一名 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'

标签: pythonpython-3.xlistpattern-matching

解决方案


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

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']

推荐阅读