python中的lambda可以迭代dict吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33077274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lambda in python can iterate dict?
提问by chyoo CHENG
I have an interview recently. The interviewer asked me the ways to iterate dict in python
. I said all the ways use forstatement. But he told me that how about lambda?
我最近有一个面试。面试官问我迭代 dict 的方法python
。我说的所有方式都用for语句。但他告诉我lambda怎么样?
I feel confused very much and I consider lambda as an anonymity function, but how it iterates a dict? some code like this:
我感到非常困惑,我认为 lambda 是一个匿名函数,但它如何迭代 dict?一些这样的代码:
new_dict = sorted(old_dict.items(), lambda x: x[1]) # sorted by value in dict
But in this code, the lambda is used as a function to provide the compared key. What do you think this question?
但在此代码中,lambda 用作提供比较键的函数。这个问题你怎么看?
采纳答案by Andrey
You don't iterate with lambda
. There are following ways to iterate an iterable object in Python:
你不迭代lambda
。在 Python 中迭代可迭代对象有以下几种方法:
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.
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
发生。
Note: 3 will not iterate it unless you iterate over that generator later. In case of 4 it depends on function.
注意: 3 不会迭代它,除非你稍后迭代那个生成器。在 4 的情况下,它取决于功能。
For iterating specific collections like dict or list there can be more techniques like while col: remove element
or with index slicing tricks.
为了迭代像 dict 或 list 这样的特定集合,可以有更多的技术,比如while col: remove element
或使用索引切片技巧。
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])
.
现在lambda
进入图片。您可以在其中的一些功能使用lambda表达式,例如:map(lambda x: x*2, [1, 2, 3])
。但是这里的 lambda 与迭代过程本身无关,可以传递一个正则函数map(func, [1, 2, 3])
。
回答by Eugene Soldatov
You can iterate dict using lambda like this:
您可以像这样使用 lambda 迭代 dict:
d = {'a': 1, 'b': 2}
values = map(lambda key: d[key], d.keys())
回答by G.S
The best way to iterate dict in python is:
在 python 中迭代 dict 的最佳方法是:
dic ={}
iter_dic = dic.iteritems().next
iter_dic()
...
iter_dic()
But you can build it with lambda func:
但是您可以使用 lambda func 构建它:
iter_dic = lambda dic: dic.keys()[0],dic.pop(dic.keys()[0])
iter_dic(dic)
...
iter_dic(dic)
回答by nperson325681
Using a plain lambda
to iterate anything in Python sounds very wrong. Certainly the most Pythonic method to iterate sequences and collections is to use list comprehensions and generator expressions like @Andrey presented.
lambda
在 Python 中使用普通来迭代任何东西听起来很错误。当然,迭代序列和集合的最 Pythonic 方法是使用列表推导式和生成器表达式,如@Andrey 所呈现的。
If the interviewer was leaning on the more theoretical/Computer Sciencey answers, it is worth noting that using lambdas to iterate is quite possible, although I must stress that this is not Pythonic nor useful at any context other than academic exercises:
如果面试官更倾向于理论/计算机科学的答案,那么值得注意的是,使用 lambdas 进行迭代是很有可能的,尽管我必须强调这不是 Pythonic,也不是学术练习以外的任何上下文中都有用:
# the legendary Y combinator makes it possible
# to let nameless functions recurse using an indirection
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
# our iterator lambda
it = lambda f: lambda Lst: (Lst[0], f(Lst[1:])) if Lst else None
# see it in action:
Y(it)([1,2,3])
=> (1, (2, (3, None)))
回答by lvc
lambda
itself doesn't iterate anything. As you thought, it just defines an anonymous function - aside from the syntactic rule about only being able to have an expression, a lambda
does nothing more than a similar function made using def
. The code inside the lambda might iterate something, but only in the same ways as any other function might use (provided they are expressions, and so valid inside a lambda
).
lambda
本身不迭代任何东西。正如你所想,它只是定义了一个匿名函数——除了关于只能有一个表达式的句法规则之外,alambda
只不过是一个使用def
. lambda 中的代码可能会迭代某些内容,但只能以与任何其他函数可能使用的方式相同的方式进行迭代(前提是它们是表达式,并且在 a 中如此有效lambda
)。
In the example you mention using sorted
, the key function is called on each element of the list being sorted - but it is sorted
itself that does this, and which does the iteration. When you provide a key function, sorted
does something broadly similar to this:
在您提到 using 的示例中sorted
,对要排序的列表的每个元素调用 key 函数 - 但它sorted
本身执行此操作,并执行迭代。当您提供一个关键功能时,会sorted
执行与此大致类似的操作:
def sorted(seq, key):
decorated = [(key(elem), i) for i, elem in enumerate(seq)]
# Sort using the normal tuple lexicographic comparisons
decorated.sort()
return [seq[i] for _,i in decorated]
As you can see, sorted
does the iteration here, not the lambda
. Indeed, there is no reason why the key hasto be a lambda - any function (or any callable) will do as far as sorted
is concerned.
如您所见,sorted
这里是迭代,而不是lambda
. 事实上,没有理由为什么键必须是一个 lambda - 任何函数(或任何可调用的)都可以sorted
。
At the lowest level, there is only really one way to iterate a dict (or, indeed, any other iterable) in Python, which is to use the iterator protocol. This is what the for
loop does behind the scenes, and you could also use a while
statement like this:
在最底层,只有一种方法可以在 Python 中迭代 dict(或者实际上是任何其他可迭代对象),那就是使用迭代器协议。这就是for
循环在幕后所做的事情,您也可以使用这样的while
语句:
it = iter(my_iterable)
while True:
try:
val = next(it)
except StopIteration:
# Run else clause of for loop
break
else:
# Run for loop body
The comments in this aren't strictly part of the iterator protocol, they are instead part of the for
loop (but having at least a loop body in there is mostly the point of iterating in the first place).
这里的注释严格来说并不是迭代器协议的一部分,而是for
循环的一部分(但至少有一个循环体主要是首先迭代的重点)。
Other functions and syntax that consume iterables (such as list, set and dict comprehensions, generator expressions or builtins like sum
, sorted
or max
) all use this protocol, by either:
使用可迭代对象的其他函数和语法(例如列表、集合和字典推导式、生成器表达式或内置函数,如sum
,sorted
或max
)都使用此协议,通过以下任一方式:
- Using a Python
for
loop, - Doing something like the above
while
loop (especially for modules written in C), - Delegating to another function or piece of syntax that uses one of these
- 使用 Python
for
循环, - 做类似上述
while
循环的事情(特别是对于用 C 编写的模块), - 委托给使用其中之一的另一个函数或语法
A class can be made so that its instances becomeiterable in either of two ways:
可以创建一个类,使其实例通过以下两种方式之一变得可迭代:
- Provide the iterator protocol directly. You need a method called
__iter__
(called byiter
), which returns an iterator. That iterator has a method called__next__
(justnext
in Python 2) which is called bynext
and returns the value at the iterator's current location and advances it (or raisesStopIteration
if it is already at the end); or - Implement part of the sequence protocol(which means behaving like a list or tuple). For forward iteration, it is sufficient to define
__getitem__
in such a way that doingmy_sequence[0]
,my_sequence[1]
, up untilmy_sequence[n-1]
(wheren
is the number of items in the sequence), and higher indexes raise an error. You usually want to define__len__
as well, which is used when you dolen(my_sequence)
.
- 直接提供迭代器协议。您需要一个被调用
__iter__
(由 调用iter
)的方法,它返回一个迭代器。该迭代器有一个被调用的方法__next__
(仅next
在 Python 2 中),它被调用next
并返回迭代器当前位置的值并推进它(StopIteration
如果它已经在最后,则提高);或者 - 实现序列协议的一部分(这意味着表现得像一个列表或元组)。对于前向迭代,
__getitem__
以这样的方式定义就足够了,执行my_sequence[0]
、my_sequence[1]
、直到my_sequence[n-1]
(其中n
是序列中的项目数)和更高的索引会引发错误。您通常也想定义__len__
,在您执行len(my_sequence)
.
回答by RamaKrishna
Dictionary iteration using lambda
使用 lambda 进行字典迭代
dct = {1: '1', 2 : '2'}
Iterating over Dictionary using lambda:
使用 lambda 迭代字典:
map(lambda x : str(x[0]) + x[1], dct.iteritems())
here x[0] is the key and x[1] is the value
这里 x[0] 是键,x[1] 是值
Result : ['11', '22']
结果:['11','22']
Filtering on Dictionary using lambda:
使用 lambda 过滤字典:
filter(lambda x : x[0] > 1, dct.iteritems())
Result : [(2, '2')]
结果:[(2, '2')]