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

时间:2018-06-04 16:08:22

标签: python python-2.7 list dictionary

我正在尝试创建一个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'}

4 个答案:

答案 0 :(得分:2)

ServletUpgradeRequest

或者,如果要使用变量,请使用{{3}}提供当前命名空间的字典,您可以使用变量名作为键。

public static class MyPathSpecCreator implements WebSocketCreator
{
    private static final String PATHSPEC_KEY = PathSpec.class.getName();

    @Override
    public Object createWebSocket(ServletUpgradeRequest upgradeRequest,
                                  ServletUpgradeResponse upgradeResponse)
    {
        String pathSpecPattern = "/"; // default value (pick your own)
        PathSpec pathSpec = (PathSpec) upgradeRequest.getServletAttribute(PATHSPEC_KEY);
        if(pathSpec != null)
            pathSpecPattern = pathSpec.getDeclaration();
        return new MyWebSocketAdapter(pathSpecPattern);
    }
}

答案 1 :(得分: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]}

答案 2 :(得分: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]}

答案 3 :(得分:-1)

@anvd, as I understood from your problem, you want to search the presence of values of dictionary d inside the lists rating1 & rating2.

Please comment, if I'm wrong or the solution that I provided below doesn't satisfy your need.

I will suggest you to create 1 more dictionary d_lists that maps the name of lists to the original list objects.

Steps:

✓ Take each key(list name) from d.

✓ Find the existence of this key in the d_lists.

✓ Take the corresponding list object from d_lists.

✓ Find the existence of value pointed by key in d inside picked list object.

✓ If element found then stop iteration and search the presence of next value in d.

✓ Print relevant messages.

Here is your modified code (with little modification)

I have shown another good example later after the below code example.

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

Output:

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

Now, have a look at another example.

Another big example:

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"

Output:

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