在Python循环中构建字典-列表和字典理解 [英] Build Dictionary in Python Loop - List and Dictionary Comprehensions

查看:83
本文介绍了在Python循环中构建字典-列表和字典理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python中的一些循环.我对使用"for"循环非常熟悉:

I'm playing with some loops in python. I am quite familiar with using the "for" loop:

for x in y:
    do something

您还可以使用循环创建一个简单列表:

You can also create a simple list using a loop:

i = []
for x in y:
   i.append(x)

,然后我最近在Stack上发现了一种不错的高效循环类型来构建列表(这种类型的循环有名称吗?我真的很想知道,因此我可以对其进行更好的搜索):

and then I recently discovered a nice efficient type of loop, here on Stack, to build a list (is there a name for this type of loop? I'd really like to know so I can search on it a little better):

[x.name for x in y]

好吧,话虽如此,我想进一步讲解最后一种循环,我尝试使用相同的逻辑类型构建python字典:

Ok, that being said, I wanted to go further with the last type of loop and I tried to build a python dictionary using the same type of logic:

{x[row.SITE_NAME] = row.LOOKUP_TABLE for row in cursor}

代替使用:

x = {}
for row in cursor:
   x[row.SITE_NAME] = row.LOOKUP_TABLE

我在等号上收到一条错误消息,告诉我这是一个无效的语法.我相信在这种情况下,这基本上是在告诉我等号是条件子句(==),而不是变量的声明.

I get an error message on the equal sign telling me it's an invalid syntax. I believe in this case, it's basically telling me that equal sign is a conditional clause (==), not a declaration of a variable.

我的第二个问题是,我可以使用这种类型的循环构建python字典吗?如果是这样,我将如何组织它?

My second question is, can I build a python dictionary using this type of loop or am I way off base? If so, how would I structure it?

推荐答案

缩写形式如下(称为 dict理解,类似于 list理解设置理解力等):

The short form is as follows (called dict comprehension, as analogy to the list comprehension, set comprehension etc.):

x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor }

因此,通常给定带有某些元素的 _container 和函数 _value ,对于给定元素,该函数将返回要添加到此键中的值字典:

so in general given some _container with some kind of elements and a function _value which for a given element returns the value that you want to add to this key in the dictionary:

{ _key : _value(_key) for _key in _container }

这篇关于在Python循环中构建字典-列表和字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆