检查值是否存在于相应的列表中

3

我正在尝试创建一个for循环,其中动态检查相应列表中是否存在某个值。我不知道是否可以将字符串转换为列表,或者是否有更好的方法来实现这一点。

rating_1 = ['no', 'yes']
rating_2 = ['no', 'yes']

for item in d:
    if d[item] not in item: # I don't want to use the item,
                            # only get name that will match the respective list above
        print "value not allowed"

d =  {'rating_2': u'no', 'rating_1': u'no'}

d 是什么样子? - user3483203
如果你想问“如何动态访问一系列具有相同名称但结尾数字不同的列表?”,那么如何创建可变数量的变量?可能会引起你的兴趣。简而言之,将它们全部保存在一个嵌套数据结构中。 - Kevin
“the respective list” 是什么意思? - jdehesa
@chrisz 问题已更新。 - anvd
@jdehesa 'rating_1' 应该与 rating_1 列表匹配。 - anvd
4个回答

2
my_lists = {
'rating_1' = ['no', 'yes'],
'rating_2' = ['no', 'yes'],
}

d =  {'rating_2': u'no', 'rating_1': u'no'}

for item in d:
    if d[item] not in my_list[item]:
        print "value not allowed"

或者,如果你想使用变量,请使用vars(),它提供了当前命名空间的字典,你可以使用变量名作为键。

rating_1 = ['no', 'yes']
rating_2 = ['no', 'yes']

d =  {'rating_2': u'no', 'rating_1': u'no'}

for item in d:
    if d[item] not in vars()[item]:
        print "value not allowed"

1
你可以使用另一种映射来允许值列表:
d =  {'rating_2': 'no', 'rating_1': 'no'}
allowed_values = {'rating_2': ['no', 'yes'], 'rating_1': ['no', 'yes']}

is_valid = all(d[item] in allowed_values[item] for item in d)

invalid_items = {k: v for k, v in d.items() if v not in allowed_values[k]}

1
你应该使用字典来存储可变数量的变量。假设你想要执行某种验证,你可以创建一个无效项的字典。一种方法是通过迭代视图 dict.items 来实现:
d =  {'rating_2': 'noo', 'rating_1': 'no'}
allowed_values = {'rating_2': ['no', 'yes'], 'rating_1': ['no', 'yes']}

bad_items = {}

for k, v in d.items():  
    if v not in allowed_values[k]:
        bad_items[k] = v

print(bad_items)

{'rating_2': 'noo'}

另一种Pythonic的方法是使用字典推导式:

bad_items = {k: v for k, v in d.items() if v not in allowed_values[k]}

显然,我不知道一些恶意用户将插入什么值来创建无效项的字典。 - anvd
当然,你可以轻松地反转逻辑;例如通过删除“not”来反转过滤器,并将其重命名为“good_items”。这取决于你想如何使用此过滤器。 - jpp

-1

@anvd,根据您的问题,您想要搜索字典d中的值是否存在于列表rating1rating2中。

如果我理解有误或者下面提供的解决方案不能满足您的需求,请评论说明。

我建议您创建另一个字典d_lists,将列表名称映射到原始列表对象。

步骤:

✓ 从d中获取每个键(列表名称)。

✓ 在d_lists中查找此键的存在。

✓ 从d_lists中获取相应的列表对象。

✓ 在选定的列表对象中查找d指向的值的存在。

✓ 如果找到元素,则停止迭代并搜索d中下一个值的存在。

✓ 打印相关消息。

这是您修改后的代码(稍作修改)

下面是另一个很好的示例。

rating_1 = ['nlo', 'yes']
rating_2 = ['no', 'yes']

# Creating a dictionary that maps list names to themselves (original list object)
d_lists = {
    "rating_1": rating_1,
    "rating_2": rating_2,
}

# Creating a dictionary that maps list to the item to be searched
# We just want to check whether 'rating_1' & 'rating_2' contains 'no' or not
d =  {'rating_2': u'no', 'rating_1': u'no'}

# Search operation using loop
for list_name in d:
    if list_name in d_lists:
        found = False
        for item in d_lists[list_name]:
            if item == d[list_name]:
                found = True
                break
        if found:
            print "'" + d[list_name] + "' exists in", d_lists[list_name];
        else:
            print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name]
    else:
        print "Couldn't find", list_name

输出:

'no' exists in ['no', 'yes']
'no' doesn't exist in ['nlo', 'yes']

现在,看另一个例子。

另一个大例子:

rating_1 = ['no', 'yes', 'good', 'best']
rating_2 = ['no', 'yes', 'better', 'worst', 'bad']
fruits = ["apple", "mango", "pineapple"]

# Creating a dictionary that maps list names to themselves (original list object)
d_lists = {
    "rating_1": rating_1,
    "rating_2": rating_2,
    "fruits": fruits,
}

# Creating a dictionary that maps list to the item to be searched
# We just want to check whether 'rating_1' & 'rating_2' contains 'no' or not
d =  {'rating_2': u'best', 'rating_1': u'good', 'fruits2': "blackberry"}

# Search operation using loop
for list_name in d:
    if list_name in d_lists:
        print "Found list referred by key/name", list_name, "=", d_lists[list_name];
        found = False
        for item in d_lists[list_name]:
            if d[list_name] == item:
                found = True
                break
        if found:
            print "'" + d[list_name] + "' exists in", d_lists[list_name], "\n";
        else:
            print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name], "\n"
    else:
        print "Couldn't find list referred by key/name ", list_name, "\n"

输出:

Found list referred by key/name rating_2 = ['no', 'yes', 'better', 'worst', 'bad']
'best' doesn't exist in ['no', 'yes', 'better', 'worst', 'bad'] 

Couldn't find list referred by key/name  fruits2 

Found list referred by key/name rating_1 = ['no', 'yes', 'good', 'best']
'good' exists in ['no', 'yes', 'good', 'best'] 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接