我正在学习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/