简体   繁体   English

如何检查元组列表是否包含所需的元素

[英]How to check if the list of tuples contains the required elements

How to check if list of tuples contains only tuples with elements ('name', 'surname', 'adress', 'car', 'colour') and ('name', 'surname', 'adress') tuple cannot exist with single 'car' and 'colour'如何检查元组列表是否仅包含具有元素的元组 ('name', 'surname', 'adress', 'car', 'colour') 和 ('name', 'surname', 'adress') 元组不能存在带有单个“汽车”和“颜色”

a =[
    ('name', 'surname', 'adres', 'car', 'colour'),
    ('name', 'surname', 'adres'),
    ('name', 'surname', 'adres', 'colour'),
    ('name', 'surname', 'adres', 'car')
]

for elem in a:
    if 'car' not in elem and 'colour' not in elem:
        print(elem)

below tuples are OK:下面的元组没问题:

('name', 'surname', 'adres', 'car', 'colour') 
('name', 'surname', 'adres')

You want to tackle this like a logic problem.您想像解决逻辑问题一样解决这个问题。 You want either (a) you find both values in the tuple or (b) neither value in the tuple.您想要 (a) 在元组中找到两个值或 (b) 在元组中都没有找到值。 You can almost code that expression into plain language like so:您几乎可以将该表达式编码为简单的语言,如下所示:

def is_valid(t):
    return ('car' in t and 'colour' in t) or ('car' not in t and 'colour' not in t)

In this case where you have such a small list of valid options, you could take the dead simple approach and just check if the tuple is one of them.在这种情况下,您有这么小的有效选项列表,您可以采用死简单的方法,只需检查元组是否是其中之一。

valid = {
    ('name', 'surname', 'adres', 'car', 'colour'),
    ('name', 'surname', 'adres')}
for elem in a:
    if elem in valid:
        print(elem)

If you want to do it algorithmically, then first you'll need to confirm that the tuple contains only the allowed elements, and contains neither or both of ('car', 'colour') , which is XNOR.如果你想用算法来做,那么首先你需要确认元组只包含允许的元素,并且不包含('car', 'colour') ,即 XNOR。

allowed = {'name', 'surname', 'adres', 'car', 'colour'}
for elem in a:
    if not all(x in allowed for x in elem):
        continue
    if ('car' in elem) ^ ('colour' in elem):
        continue
    print(elem)

(I broke it up to keep the lines under 80 chars) (我将其分解以将行保持在 80 个字符以下)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM