除了在每组变量之间进行比较之外,是否有更好的方法来比较三个列表的长度以确保它们的大小都相同?如果我想检查十个列表的长度是否相等怎么办。我该怎么做呢?
问问题
26908 次
3 回答
23
使用all()
:
length = len(list1)
if all(len(lst) == length for lst in [list2, list3, list4, list5, list6]):
# all lists are the same length
或者找出是否有任何列表具有不同的长度:
length = len(list1)
if any(len(lst) != length for lst in [list2, list3, list4, list5, list6]):
# at least one list has a different length
请注意,all()
andany()
会短路,例如,如果list2
长度不同,它将不会执行list3
through的比较list6
。
如果您的列表存储在列表或元组中而不是单独的变量中:
length = len(lists[0])
if all(len(lst) == length for lst in lists[1:]):
# all lists are the same length
于 2013-05-23T18:05:40.840 回答
4
假设您的列表存储在列表中(称为my_lists
),请使用以下内容:
print len(set(map(len, my_lists))) <= 1
这会计算您拥有的所有列表的长度,my_lists
并将这些长度放入一个集合中。如果它们都相同,则该集合将包含一个元素(或零,您没有列表)。
于 2013-05-23T18:06:34.333 回答
1
一个班轮使用itertools.combinations()
import itertools
l1 = [3,4,5]
l2 = [4,5,7]
l3 = [5,6,7,8,3]
L = [l1, l2, l3]
verdict = all([len(a)==len(b) for a,b in list(itertools.combinations(L,2))])
列表的第一个构建列表,L
. 然后从 L 中查询所有两个元素的集合list(itertools.combinations(L,2))
:
>>> list(itertools.combinations(L,2))
[([3, 4, 5], [4, 5, 7]), ([3, 4, 5], [5, 6, 7, 8, 3]),
([4, 5, 7], [5, 6, 7, 8, 3])]
然后测试此列表中每一对的长度。最后,取布尔值的交集,与all()
.
>>> verdict
False
哪个是对的。让我们尝试相同大小的尝试列表。
l1 = [3,4,5]
l2 = [4,5,7]
l3 = [5,6,7]
L = [l1, l2, l3]
verdict=all([len(a)==len(b) for a,b in list(itertools.combinations(L,2))])
我们得到
>>> verdict
True
于 2013-05-23T18:21:11.333 回答