【问题标题】:Verify string exists as key or value in Python dictionary?验证字符串作为键或值存在于 Python 字典中吗?
【发布时间】:2017-12-18 23:30:20
【问题描述】:

我正在为 linux 目录构建一个爬虫/爬虫。本质上,该程序将获取用户输入的文件类型以进行抓取 (这就是我的问题所在)

我将可接受的文件扩展名类型存储在带有嵌套列表的字典中,例如:

file_types = {'images': ['png', 'jpg', 'jpeg', 'gif', 'bmp'], 'text': ['txt', 'doc', 'pdf']}

为了让用户可以选择哪些选项,我使用了这个 for 循环:

for k, v in file_types.items():
    print(k, v)

以这种格式打印字典:

audio ['mp3', 'mpa', 'wpi', 'wav', 'wpi']

text ['txt', 'doc', 'pdf']

video ['mp4', 'avi', '3g2', '3gp', 'mkv', 'm4v', 'mov', 'mpg', 'wmv', 'flv']

images ['png', 'jpg', 'jpeg', 'gif', 'bmp']

现在如果我这样做:

scrape_for = input("Please enter either the type of file, or the extension you would like to scrape for: \n")

如何验证用户输入是否存在于我的字典 file_types 中作为键或值(我说键或值,因此如果用户输入“图像”,我可以使用键图像的值)

【问题讨论】:

  • 一种不那么 Python 的方法:key if key in file_types else reduce(lambda p,n: p or n if key in n else False, file_types.values(), False)

标签: python python-3.x dictionary


【解决方案1】:

使用 Python 酷炫的列表推导式制作扩展列表

list_of_extensions = [ item \
    for extensionList in file_types.values() \
    for item in extensionList
]

现在使用惯用的 Python 构造 item in list_var,如果该项目存在于该列表中,则计算结果为 True,以及 or

if scrape_for in file_types or scrape_for in list_of_extensions:
    # do something
else:
    print("Unsupported file type: " + scrape_for)

注意:在字典名称上使用in 运算符等效于(实际上)scrape_for in file_types.keys()

【讨论】:

    【解决方案2】:

    我会先将扩展列表扁平化为一个集合,这样您以后就不必循环遍历它,并且可以进行快速的现场查找:

    file_types = {'images': ['png', 'jpg', 'jpeg', 'gif', 'bmp'], 'text': ['txt', 'doc', 'pdf']}
    file_extensions = set(sum(file_types.values(), []))
    
    scrape_for = input("Enter the type / extension to scrape: ").lower()
    if scrape_for not in file_types and scrape_for not in file_extensions:
        print("I don't support this type / extension!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2013-07-02
      • 2019-11-22
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多