我是python和编程的新手,需要一些帮助:我有一个我之前在程序中创建的列表,通过循环附加(即我现在不能重新定义我的列表来解决我的问题),24个4元组:
elementary = [(23, 1, 18, 4), (23, 1, 6, 16), (23, 1, 4, 18), (23, 2, 18, 3), (23, 2, 12, 9), (23, 2, 9, 12), (23, 2, 3, 18), (23, 3, 18, 2), (23, 3, 2, 18), (23, 4, 18, 1), (23, 4, 1, 18), (23, 5, 14, 7), (23, 5, 7, 14), (23, 6, 16, 1), (23, 6, 9, 8), (23, 6, 8, 9), (23, 6, 1, 16), (23, 7, 14, 5), (23, 7, 5, 14), (23, 8, 9, 6), (23, 8, 6, 9), (23, 9, 12, 2), (23, 9, 8, 6), (23, 9, 6, 8), (23, 9, 2, 12), (23, 12, 9, 2), (23, 12, 2, 9), (23, 14, 7, 5), (23, 14, 5, 7), (23, 16, 1, 6), (23, 18, 4, 1), (23, 18, 3, 2), (23, 18, 2, 3), (23, 18, 1, 4)]
但现在想要摆脱刚刚重新安排的元组...换句话说,在第一个元组((23,1,18,4)
)之后我会放弃(23,1,4,18), (23,4,1,18)
等等......,如果可能的话,我想在整个列表中这样做,这样我最终只会得到6个完全不同的4元组。有没有办法做到这一点,而不是在我的程序中先回去做一些不同的事情?任何帮助将不胜感激。谢谢!
答案 0 :(得分:3)
怎么样:
{tuple(sorted(t)): t for t in elementary}.values()
答案 1 :(得分:2)
作为1-liner,对每个4元组进行排序,然后创建一组结果,shich具有删除重复的效果。我假设你的4元组被允许改变元素的顺序。
set(tuple(sorted(i)) for i in elementary)
>>> set((5, 7, 14, 23), (6, 8, 9, 23), (2, 3, 18, 23), (1, 4, 18, 23), (1, 6, 16, 23), (2, 9, 12, 23))
答案 2 :(得分:0)
elementary_unique = set(tuple(sorted(t)) for t in elementary)
现在elementary_unique
是一个集合而不是列表 - 如果重要,可以使用
elementary_unique = list(set(tuple(sorted(t)) for t in elementary))
相反,但这会比第一个版本慢一点。
答案 3 :(得分:0)
您可以在sorted(tuple1) == sorted(tuple2)
时识别等效组合。
代码很简短:
>>> set(map(tuple, map(sorted, elementary)))
set([(5, 7, 14, 23), (6, 8, 9, 23), (2, 3, 18, 23),
(1, 4, 18, 23), (1, 6, 16, 23), (2, 9, 12, 23)])
如果你需要保留每个第一个不同元组的顺序,那么需要更多的工作:
>>> uniq = set()
>>> for t in elementary:
s = tuple(sorted(t))
if s not in uniq:
uniq.add(s)
print t
(23, 1, 18, 4)
(23, 1, 6, 16)
(23, 2, 18, 3)
(23, 2, 12, 9)
(23, 5, 14, 7)
(23, 6, 9, 8)
答案 4 :(得分:0)
如果你真的想通过比较来解决这个问题:
In [1028]: elementary = [(23, 1, 18, 4), (23, 1, 6, 16), (23, 1, 4, 18), (23, 2, 18, 3), (23, 2, 12, 9), (23, 2, 9, 12), (23, 2, 3, 18), (23, 3, 18, 2), (23, 3, 2, 18), (23, 4, 18, 1), (23, 4, 1, 18), (23, 5, 14, 7), (23, 5, 7, 14), (23, 6, 16, 1), (23, 6, 9, 8), (23, 6, 8, 9), (23, 6, 1, 16), (23, 7, 14, 5), (23, 7, 5, 14), (23, 8, 9, 6), (23, 8, 6, 9), (23, 9, 12, 2), (23, 9, 8, 6), (23, 9, 6, 8), (23, 9, 2, 12), (23, 12, 9, 2), (23, 12, 2, 9), (23, 14, 7, 5), (23, 14, 5, 7), (23, 16, 1, 6), (23, 18, 4, 1), (23, 18, 3, 2), (23, 18, 2, 3), (23, 18, 1, 4)]
In [1029]: for e in elementary:
add = True
for a in answer:
if all(_e in a and e.count(_e)==a.count(_e) and len(e)==len(a) for _e in e):
add = False
if add:
answer.append(e)
In [1030]: answer
Out[1030]:
[(23, 1, 18, 4),
(23, 1, 6, 16),
(23, 2, 18, 3),
(23, 2, 12, 9),
(23, 5, 14, 7),
(23, 6, 9, 8)]