Remove Tuple if it Contains any Empty String Elements

可紊 提交于 2019-12-01 08:58:47

问题


There have been questions asked that are similar to what I'm after, but not quite, like Python 3: Removing an empty tuple from a list of tuples, but I'm still having trouble reading between the lines, so to speak.

Here is my data structure, a list of tuples containing strings

data
>>[
('1','1','2'),
('','1', '1'),
('2','1', '1'),
('1', '', '1')
]

What I want to do is if there is an empty string element within the tuple, remove the entire tuple from the list.

The closest I got was:

data2 = any(map(lambda x: x is not None, data))

I thought that would give me a list of trues' and falses' to see which ones to drop, but it just was a single bool. Feel free to scrap that approach if there is a better/easier way.


回答1:


You can use filter - in the question you linked to None is where you put a function to filter results by. In your case:

list(filter(lambda t: '' not in t, data))

t ends up being each tuple in the list - so you filter to only results which do not have '' in them.




回答2:


You can use list comprehension as follows:

data = [ ('1','1','2'), ('','1', '1'), ('2','1', '1'), ('1', '', '1') ]
data2 = [_ for _ in data if '' not in _]
print(data2)

output:

[('1', '1', '2'), ('2', '1', '1')]


来源:https://stackoverflow.com/questions/47426337/remove-tuple-if-it-contains-any-empty-string-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!