如果元组包含任何空字符串元素,则删除它 [英] Remove Tuple if it Contains any Empty String Elements

查看:15
本文介绍了如果元组包含任何空字符串元素,则删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些问题与我所追求的类似,但不完全是,例如 Python 3:从元组列表中删除一个空元组,但可以这么说,我仍然无法在两行之间阅读.

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.

我得到的最接近的是:

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

我认为这会给我一个 true 和 false 列表,以查看要删除哪些,但它只是一个布尔值.如果有更好/更简单的方法,请随意放弃该方法.

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.

推荐答案

您可以使用 filter - 在您链接到 None 的问题中,您可以在其中放置一个函数过滤结果.在你的情况下:

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 最终成为 list 中的每个元组 - 因此您只过滤到其中没有 '' 的结果.

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

这篇关于如果元组包含任何空字符串元素,则删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆