python - python中这一行表达式的解释

标签 python python-3.x

我正在学习python,看到了一行python表达式,但是不太懂。有人可以帮我解释一下代码吗?或者在传统的 for 循环中扩展代码?更具体地说,{fruit: 是什么意思?

return {fruit: basket.count(fruit) for fruit in set(basket)}

谢谢!

最佳答案

这个表达式称为字典理解(本质上是创建字典的单行表达式)。

在 Python 中,字典看起来像这样:

dictionary = {"key": "value", "anotherkey": ["some", "other", "value"]}

其中:的右侧是键(通常是字符串),:的左侧是分配给该键的值。

您可以使用字典从键中获取值,如下所示:

dictionary["key"]
>> "value"

因此,字典理解使用某种表达式(如示例中的表达式)构建字典。

如果您有这个篮子:

basket = ["apple", "apple", "banana"]
set(basket)  # set() returns a set of unique items from basket.
>> {"apple", "banana"} 
basket.count("apple")  # list.count(x) returns the number of times x occurs in list.
>> 2

这个:

dictionary = {}
for fruit in set(basket):
    dictionary[fruit] = basket.count(fruit)
return dictionary

与此相同:

return {fruit: basket.count(fruit) for fruit in set(basket)}
#      {^key : ^value}  is added   for each item in set(basket)           

他们都返回:

{"apple": 2, "banana": 1}

关于python - python中这一行表达式的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066464/

相关文章:

Python txt 文件字数统计程序

python - 将 python 3 中的生成器与 +-operator 连接起来

python - python twitter Streamer 中的引号问题

python - 将我的 Python 应用程序部署到 Heroku 会破坏 Heroku 的 Python 解释器

python - 如何在Python中并行运行多个进程

Python pandas 没有属性 ols - 错误(滚动 OLS)

python - 匹配多个包含括号内文本的完整 HTML 段落

python - 使用其他类的默认初始化值

python - 将数据帧保存到多个保留数据帧名称的 CSV

python - 在模板 Django 中使用包含数字作为范围的 for 循环