gpt4 book ai didi

python - 1 liner 'pythonic' 返回集合而不是列表的代码

转载 作者:太空狗 更新时间:2023-10-30 01:51:03 25 4
gpt4 key购买 nike

我想做下面的代码,除了在一个整洁的 1-liner 中:

terms_set = set([])
for term in terms:
if index.has_key(term):
terms_set.add(index[term])

可以吗?必须退回一套。

最佳答案

您可以使用集合理解:

terms_set = {index[term] for term in terms if term in index}

请注意,字典中的键优于dict.has_key,后者was deprecated in Python 2并且在 Python 3 中不可用。

关于python - 1 liner 'pythonic' 返回集合而不是列表的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28145024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com