如何检查 list/matrix 中的所有项目在 python 中是否不同
how to check all items in a list/matrix are different in python
给定一个 NxN 列表矩阵,我如何确定列表中的所有元素都是唯一的
输入示例:
(check_unique_elem([[8, 3, 4], [1, 5, 9], [6, 7, 2]]))
example output:
True
(check_unique_elem([[1]]))
True
(check_unique_elem([[2,3],[6,5],[6,7]]))
False
如果元素都是可散列的(您示例中的整数是),您可以将它们添加到集合中以检查重复项。
def check_unique_elem(L):
seen = set()
for row in L:
for i in row:
if i in seen:
return False
seen.add(i)
return True
这样做的好处是一旦找到第一个重复项就退出(短路)
不是最优的,但简洁:
def check_unique_elem(mat):
flat = [c for row in mat for c in row]
return len(flat) == len(set(flat))
也不太容易受到定时攻击,在极不可能的情况下这是一个问题
或者如果你想要一个单线:
import collections
has_duplicate = collections.Counter(c for row in mat for c in row).most_common(1)[0][1] > 1
from itertools import chain
print(len(set(chain(*l))) == sum(len(s) for s in l))
如果您的列表非常大,有更有效的方法,如果不是,那么这是一种简洁的方法来完成您想要的。
有点像代码高尔夫,但我们可以在子列表的基础上短路:
l = [[8, 3, 4], [7, 5, 9], [33, 12, 22]]
st = set()
print(not any(b == -1 for b in (st.update(s) if st.isdisjoint(s) else -1
for s in map(set, l))))
也许:
def check_unique_elem(mylist):
flattened_list = [i for sublist in mylist for i in sublist]
return len(set(flattened_list)) == len(flattened_list)
print(check_unique_elem([[8, 3, 4], [1, 5, 9], [6, 7, 2]]))
print(check_unique_elem([[1]]))
print(check_unique_elem([[2,3],[4,5],[6,7]]))
将所有内容存储在一个列表中,然后使用 count:
检查每个元素的出现
def elements_are_unique(new_list):
for element in new_list:
icount = new_list.count(element)
if icount > 1:
return False
return True
给定一个 NxN 列表矩阵,我如何确定列表中的所有元素都是唯一的 输入示例:
(check_unique_elem([[8, 3, 4], [1, 5, 9], [6, 7, 2]]))
example output:
True
(check_unique_elem([[1]]))
True
(check_unique_elem([[2,3],[6,5],[6,7]]))
False
如果元素都是可散列的(您示例中的整数是),您可以将它们添加到集合中以检查重复项。
def check_unique_elem(L):
seen = set()
for row in L:
for i in row:
if i in seen:
return False
seen.add(i)
return True
这样做的好处是一旦找到第一个重复项就退出(短路)
不是最优的,但简洁:
def check_unique_elem(mat):
flat = [c for row in mat for c in row]
return len(flat) == len(set(flat))
也不太容易受到定时攻击,在极不可能的情况下这是一个问题
或者如果你想要一个单线:
import collections
has_duplicate = collections.Counter(c for row in mat for c in row).most_common(1)[0][1] > 1
from itertools import chain
print(len(set(chain(*l))) == sum(len(s) for s in l))
如果您的列表非常大,有更有效的方法,如果不是,那么这是一种简洁的方法来完成您想要的。
有点像代码高尔夫,但我们可以在子列表的基础上短路:
l = [[8, 3, 4], [7, 5, 9], [33, 12, 22]]
st = set()
print(not any(b == -1 for b in (st.update(s) if st.isdisjoint(s) else -1
for s in map(set, l))))
也许:
def check_unique_elem(mylist):
flattened_list = [i for sublist in mylist for i in sublist]
return len(set(flattened_list)) == len(flattened_list)
print(check_unique_elem([[8, 3, 4], [1, 5, 9], [6, 7, 2]]))
print(check_unique_elem([[1]]))
print(check_unique_elem([[2,3],[4,5],[6,7]]))
将所有内容存储在一个列表中,然后使用 count:
检查每个元素的出现def elements_are_unique(new_list):
for element in new_list:
icount = new_list.count(element)
if icount > 1:
return False
return True