【问题标题】:Python 3: Find an element in a list inside a dictionaryPython 3:在字典内的列表中查找元素
【发布时间】:2017-03-29 03:24:33
【问题描述】:
houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}

例如,我需要检查然后找到 20 个。

已经尝试了几个小时。
如果您能提供解释和多种解决方案,那就太好了。
提前致谢。

【问题讨论】:

  • print(20 in houses['others']) ?
  • 你可以使用any: any(20 in v for k, v in houses.items()
  • 我在上一条评论中漏掉了一个右括号,应该是:any(20 in v for k, v in houses.items())
  • 谢谢阿法辛。有用。但是我一般都找不到我想要的吗?如果我不知道 20 在字典的另一个列表中怎么办?
  • @ArthurTacca 它不能始终如一地工作。一旦我得到一个 True ,下一个我得到 TypeError: argument of type 'int' is not iterable.

标签: list python-3.x dictionary


【解决方案1】:

您的housesdictionary。但是它缺少}。它的others 键是list,因此您可以像这样访问它的第一项:print (houses['others'][0])。如果您需要遍历键和值,有几种方法,如此链接所示:Iterating over dict values .一个基本的版本是这样的:

houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}
bool = False
for (k,v) in houses.items():
    if type(v)==list:
        if 20 in v:
            bool = True
            print(k,v)
    if v == 20:
        bool = true
        print(k,v)
print(bool)

【讨论】:

【解决方案2】:

这将查看houses 中的所有条目,并在值中查找search。对于每一个值,如果不是集合,则直接比较。

def is_in_house(search, house):
    for v in houses.values():
        try:
            if search in v:
                return True
        except TypeError:
            if v == search:
                return True
    return False

【讨论】:

    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2021-12-14
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多