简体   繁体   English

Python:内联是否打印非空字符串?

[英]Python: Inline if to print non-empty strings?

I'm trying to print out just the non-empty strings in a list. 我正在尝试打印列表中的非空字符串。 I can't seem to get the below to work, what am I doing wrong?? 我似乎无法让下面的工作,我做错了什么?

print item in mylist if item is not ""

The following is invalid syntax: print item in mylist if item is not "" 以下是无效语法: print item in mylist if item is not ""

You could perhaps achieve what you want using a list comprehension: 您可以使用列表理解来实现您想要的目标:

>>> mylist = ["foo","bar","","baz"]
>>> print [item for item in mylist if item]
['foo', 'bar', 'baz']

You could create a generator to grab the items in the list that are not empty. 您可以创建一个生成器来抓取列表中非空的项目。

nonempties = (item for item in mylist if item)

Then loop and print or join them into a string. 然后循环并打印或将它们连接成一个字符串。

print ' '.join(nonempties)

The filter() built-in is well suited for exactly that, just pass None instead of a function: 内置的filter()非常适合,只需传递None而不是函数:

>>> filter(None, ['Abc', '', 'def', None, 'ghi', False, 'jkl'])
['Abc', 'def', 'ghi', 'jkl']

Details at http://docs.python.org/library/functions.html 有关详细信息,请访问http://docs.python.org/library/functions.html

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

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