我在列表中的列表中删除元组时遇到问题。基本上我有这个:
a = [[(4, 7), (4, 5)], [], [], [], [], [(4, 1)], [(4, 5), (4, 3)], [], [], [], [], [(4, 3), (4, 1)]]
我只想要每个元组一次。我也想删除空列表,类似的东西:
b = [[(4, 7)],[(4, 1)],[(4, 5)],[(4, 3)]]
顺序并不重要,但它不仅仅适用于这个特定的列表(我希望代码能够处理由列表中包含许多元组的列表组成的列表)。 我试过set()但我无法弄清楚它是如何工作的。
答案 0 :(得分:4)
Itertools救援:
from itertools import chain
list(set(chain.from_iterable(a)))
[(4, 5), (4, 7), (4, 1), (4, 3)]
如果嵌套非常重要:
[[t] for t in set(chain(*a))]
答案 1 :(得分:1)
from itertools import chain
[[x] for x in set(chain(*a))]
答案 2 :(得分:0)
我想你想要这样的东西:
inp = [[(4, 7), (4, 5)], [], [], [], [], [(4, 1)], [(4, 5), (4, 3)], [], [], [], [], [(4, 3), (4, 1)]]
out = []
for lst in inp:
for tup in lst:
if [tup] not in out:
out.append([tup])
print out
[[(4, 7)], [(4, 5)], [(4, 1)], [(4, 3)]]