【发布时间】:2021-03-22 23:14:22
【问题描述】:
我有一组元组,例如set_of_tuples = {(1,2}, (1,3), (1,), (4,3)} 我想删除所有包含例如 1 的元组,我想知道有多少. 如何有效地做到这一点?
我的做法:
set_of_tuples={(1,2),(1,3),(1,),(4,3)}
to_be_removed = set()
i=0
for val in set_of_tuples:
if 1 in val:
i=i+1
to_be_removed.add(val)
set_of_tuples = set_of_tuples-to_be_removed
【问题讨论】:
-
你试过
set_of_tuples = {s for s in set_of_tuples if 1 not in s}吗? -
如果您想知道删除了多少,请保存之前的集合长度并减去结果长度。
-
不...非常感谢!