python中的lambda可以迭代dict吗? [英] lambda in python can iterate dict?
问题描述
我最近有一次采访.面试官问我如何迭代python
中的dict.我说过所有方式都使用 for 语句.但是他告诉我 lambda 怎么样?
I have an interview recently. The interviewer asked me the ways to iterate dict in python
. I said all the ways use for statement. But he told me that how about lambda?
我感到非常困惑,我认为lambda是一个匿名函数,但是如何迭代dict?像这样的一些代码:
I feel confused very much and I consider lambda as an anonymity function, but how it iterates a dict? some code like this:
new_dict = sorted(old_dict.items(), lambda x: x[1]) # sorted by value in dict
但是在此代码中,lambda用作提供比较键的函数.您如何看待这个问题?
But in this code, the lambda is used as a function to provide the compared key. What do you think this question?
推荐答案
您不必使用lambda
进行迭代.有以下几种在Python中迭代可迭代对象的方法:
You don't iterate with lambda
. There are following ways to iterate an iterable object in Python:
-
for
陈述(您的答案) - 理解,包括列表
[x for x in y]
,字典{key: value for key, value in x}
和设置{x for x in y}
- 生成器表达式:
(x for x in y)
- 传递将对其进行迭代的函数(
map
,all
,itertools
模块) - 手动调用
next
函数,直到StopIteration
发生.
for
statement (your answer)- Comprehension, including list
[x for x in y]
, dictionary{key: value for key, value in x}
and set{x for x in y}
- Generator expression:
(x for x in y)
- Pass to function that will iterate it (
map
,all
,itertools
module) - Manually call
next
function untilStopIteration
happens.
注意:3不会对其进行迭代,除非您稍后对该生成器进行迭代.如果是4,则取决于功能.
Note: 3 will not iterate it unless you iterate over that generator later. In case of 4 it depends on function.
要遍历dict或list之类的特定集合,可以使用诸如while col: remove element
或带有索引切片技巧的更多技术.
For iterating specific collections like dict or list there can be more techniques like while col: remove element
or with index slicing tricks.
现在lambda
出现在图片中.您可以在其中一些函数中使用lambda,例如:map(lambda x: x*2, [1, 2, 3])
.但是这里的lambda与迭代过程本身无关,您可以传递常规函数map(func, [1, 2, 3])
.
Now lambda
comes into the picture. You can use lambdas in some of those functions, for example: map(lambda x: x*2, [1, 2, 3])
. But lambda here has nothing to do with iteration process itself, you can pass a regular function map(func, [1, 2, 3])
.
这篇关于python中的lambda可以迭代dict吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!