简体   繁体   English

如何使用lambda打印字符串列表?

[英]How to print list of strings with lambda?

I have a list of strings that print out just fine using a normal loop: 我有一个使用正常循环可以正常打印的字符串列表:

for x in listing:
    print(x)

I thought it should be pretty simple to use a lambda to reduce the loop syntax, and kickstart my learning of lambdas in Python (I'm pretty new to Python). 我认为使用lambda减少循环语法应该很简单,并开始在Python中学习lambda(对于Python来说我是很新的)。

Given that the syntax for map is map(function, iterable, ...) I tried: 鉴于 map 的语法map(function, iterable, ...)我尝试过:

map(lambda x: print(x), listing)

But this does not print anything out (it also does not produce an error). 但这不会打印出任何内容(它也不会产生错误)。 I've done some searching through material online but everything I have found to date is based on Python 2, namely mentioning that with Python 2 this isn't possible but that it should be in Python 3, without explicitly mentioning how so. 我已经在网上进行了一些搜索,但是到目前为止,我发现的所有内容都是基于Python 2的,也就是说,提到使用Python 2是不可能的,但是应该在Python 3中进行,而没有明确提及如何做到这一点。

What am I doing wrong? 我究竟做错了什么?

In python 3, map returns an iterator: 在python 3中, map返回一个迭代器:

>>> map(print, listing)
<map object at 0x7fabf5d73588>

This iterator is lazy , which means that it won't do anything until you iterate over it. 该迭代器是惰性的 ,这意味着除非您对其进行迭代,否则它不会做任何事情。 Once you do iterate over it, you get the values of your list printed: 对其进行迭代后,您将获得打印列表的值:

>>> listing = [1, 2, 3]
>>> for _ in map(print, listing):
...     pass
... 
1
2
3

What this also means is that map isn't the right tool for the job. 这也意味着map不是完成任务的正确工具。 map creates an iterator, so it should only be used if you're planning to iterate over that iterator. map创建了一个迭代器,因此仅当您计划迭代该迭代器时才应使用它。 It shouldn't be used for side effects, like printing values. 不应将其用于副作用,例如打印值。 See also When should I use map instead of a for loop . 另请参阅何时应该使用map而不是for循环

I wouldn't recommend using map here, as you don't really care about the iterator. 我不建议在这里使用map ,因为您并不真正在乎迭代器。 If you want to simplify the basic "for loop", you could instead use str.join() : 如果要简化基本的“ for循环”,则可以改用str.join()

>>> mylist = ['hello', 'there', 'everyone']
>>> '\n'.join(mylist)
hello
there
everyone

Or if you have a non-string list: 或者,如果您有非字符串列表:

>>> mylist = [1,2,3,4]
>>> '\n'.join(map(str, mylist))
1
2
3
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM