有一个函数可以用来替换我的 if 语句和变量吗?

问题描述 投票:0回答:2

我正在尝试找出如何使我的代码更具可读性并且代码中的行数更少。它包含很多 if elif 语句,看起来可以合并成几个。

fl = input("file:").lower().strip()

a = fl.endswith(".jpeg")
b = fl.endswith(".jpg")
c = fl.endswith(".txt")
d = fl.endswith(".png")
e = fl.endswith(".pdf")
f = fl.endswith(".zip")
g = fl.endswith(".gif")

if a or b is True:
    print("image/jpeg")
elif c is True:
    print("text/plain")
elif d is True:
    print("image/png")
elif e is True:
    print("application/pdf")
elif f is True:
    print("application/zip")
elif g is True:
    print("image/gif")
else:
    print("application/octet-stream")

我尝试通过将

fl == fl.endswith(".filetype")
放入 if 语句中来摆脱顶部的变量,而不是打印每种类型,而是只打印我的 else 语句。我还尝试在 python 文档中查找其他方法来获取 str 的结尾,但找不到任何内容。不要给我太直接的问题解决方案,想避免cs50学术诚信问题。对 python 来说还很陌生

python cs50
2个回答
0
投票

创建将文件扩展名映射到内容类型的字典可能是最简单/最干净的:

extensions = {
    '.jpeg': 'image/jpeg',
    '.jpg': 'image/jpeg',
    '.txt': 'text/plain',
    # etc etc etc
}

for extension, content_type in extensions.items():
    if fl.endswith(extension):
        print(content_type)

0
投票

你可以使用字典:

extensions = {
    "image/jpeg": (".jpeg", ".jpg"),
    "text/plain": (".txt",),
    "image/png": (".png",),
    "appllication/pdf": (".pdf",),
    "appllication/zip": (".zip",),
    "image/gif": (".gif",),
}

expected_mime_type = "application/octet-stream"
for mime_type, extensions in extensions.items():
    if fl.endswith(extensions):  # <- can use multiple here
        expected_mime_type = mime_type
        break

print(expected_mime_type)
© www.soinside.com 2019 - 2024. All rights reserved.