我正在尝试从数组打印一组唯一的数组,同时保持数组顺序。
示例数组:
[[1,2,3], [1,3,2], [1,2,3], [3,1,2]]
我正在寻找的输出是:
[[1,2,3], [1,3,2], [3,1,2]]
我已经考虑过将数组转换为一个集合,但它似乎存在二维数组的问题(我相信它会单独比较每个元素,如果它可以运行,它将导致简单的[1,2,3]
)另外,我读到它没有保持数值的顺序。
答案 0 :(得分:0)
使用嵌套的for循环查看是否已经看到某个元素:
data = [[1,2,3], [1,3,2], [1,2,3], [3,1,2]]
processed = []
for i in range(len(data)):
for j in range(i):
if data[i] == data[j]:
break
else:
processed.append(data[i])
print(processed) # Should be [[1,2,3], [1,3,2], [3,1,2]]
答案 1 :(得分:0)
您需要简单检查数组其余部分中是否有元素并将其删除。为了保持秩序,循环应该倒退:
array = [[1,2,3], [1,3,2], [1,2,3], [3,1,2]]
for a_ind in range((len(array)-1), 0, -1):
if (array[a_ind] in array[:a_ind]):
array.pop(a_ind)
print (array)
# [[1, 2, 3], [1, 3, 2], [3, 1, 2]]
答案 2 :(得分:0)
尝试这样的事情:
>>> u = [[1,2,3], [1,3,2], [1,2,3], [3,1,2]]
>>> unique = []
>>> (unique.append(x) for x in u if x not in unique)
<generator object <genexpr> at 0x103df4620>
>>> print(unique)
[[1, 2, 3], [1, 3, 2], [3, 1, 2]]
答案 3 :(得分:0)
您可以:
而不是for循环Item
class Foo(object):
def __init__(self, a_list):
self._list = list(a_list)
def __str__(self):
return str(self._list)
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return all([i1 == i2 for i1, i2 in zip(self, other)])
def __ne__(self, other):
return any([i1 != i2 for i1, i2 in zip(self, other)])
def __hash__(self):
return 0
def __iter__(self):
return iter(self._list)
a1 = Foo([1, 2, 3])
a2 = Foo([1, 3, 2])
a3 = Foo([1, 2, 3])
a4 = Foo([3, 2, 1])
c = [a1, a2, a3, a4]
print(list(set(c)))
# Output
[[1, 2, 3], [1, 3, 2], [3, 2, 1]]
和__str__
方法用于输出,__repr__
用于列表推导。
答案 4 :(得分:0)
a = [[1, 2, 3], [1, 3, 2], [1, 2, 3], [3, 1, 2]]
d = {}
for k in a:
d[str(k)] = k
a = []
for v in d.values():
a += [v]
print(a)
输出*
[[1,3,2],[1,2,3],[3,1,2]]
b = [[1, 2, 3], [1, 3, 2], [1, 2, 3], [3, 1, 2]]
for l in b:
if l in b[b.index(l) + 1:]:
b.pop(b.index(l))
print(b)
输出
[[1,3,2],[1,2,3],[3,1,2]]