【问题标题】:Check if value is present in respective list检查相应列表中是否存在值
【发布时间】:2018-11-14 00:46:59
【问题描述】:

我正在尝试创建一个 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 长什么样子?
  • 如果您要问“给定一系列列表,除了末尾不同的数字外,所有列表都具有相同的名称,我如何动态访问每个列表?”,那么How do I create a variable number of variables? 可能会感兴趣给你。短版:将它们全部保存在一个嵌套数据结构中。
  • “相应列表”是什么意思?
  • @chrisz 问题已更新。
  • @jdehesa 'rating_1' 应该匹配 rating_1 列表

标签: python python-2.7 list dictionary


【解决方案1】:

✓ @anvd,我从您的问题中了解到,您想在列表 rating1 中搜索字典 d 的值是否存在& 评级2。

如果我错了或者我在下面提供的解决方案不能满足您的需求,请发表评论。

我建议您再创建 1 个字典 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'] 

【讨论】:

    【解决方案2】:

    您可以对允许的值列表使用另一个映射:

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

    【讨论】:

      【解决方案3】:
      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"
      

      【讨论】:

        【解决方案4】:

        您应该为可变数量的变量使用字典。假设您正在寻找执行某种验证,您可以创建一个无效项目的字典。一种方法是通过迭代视图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]}
        

        【讨论】:

        • 显然,我不知道某些恶意用户会插入什么值来创建无效项目字典。
        • 当然,你可以很容易地反转逻辑;例如通过删除not 来反转过滤器;并重命名为good_items。真的取决于你想如何使用这个过滤器。
        猜你喜欢
        • 2020-06-15
        • 1970-01-01
        • 2018-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-06
        • 2019-02-13
        • 2019-05-28
        相关资源
        最近更新 更多