[英]Check if the lengths inside a nested list are identical
I have a list of lists and I want to calculate first the size of each sub-list and then to see whether all those sub-lists have size 2. Therefore, 我有一个列表列表,我想首先计算每个子列表的大小,然后查看所有这些子列表是否大小为2.因此,
my_list = [["obj1", "item1"], ["obj2", "item2", "item1"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
lengths = [len(x) for x in my_list]
The list lengths
contains the size of each sub-list. 列表
lengths
包含每个子列表的大小。 How can I check whether all my sub-lists have size two or not? 如何检查我的所有子列表是否大小为2? In my example it should fail.
在我的例子中它应该失败。
Use all
with a generator expression. 使用
all
表达式生成器。
>>> my_list = [[1, 2], [3, 4], [5]]
>>> all(len(sub) == 2 for sub in my_list)
False
>>>
>>> my_list[-1].append(6)
>>> all(len(sub) == 2 for sub in my_list)
True
Or if the length does not have to be two specificly: 或者如果长度不必特别是两个:
>>> subs = iter(my_list)
>>> len_ = len(next(subs))
>>> all(len(sub) == len_ for sub in subs)
True
You can identify the number of unique elements in a list by converting it to a set
. 您可以通过将列表转换为
set
来标识列表中唯一元素的数量。 If the length of the set is 1, and the only element of the set is 2, then you know that every list had length 2. 如果集合的长度为1,并且集合中唯一的元素是2,那么您知道每个列表的长度为2。
my_list = [["obj1", "item1"], ["obj2", "item2", "item1"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
lengths = [len(x) for x in my_list]
print(set(lengths))
# {2, 3}
len(set(lengths)) == 1 and set(lengths).pop() == 2
# False
You could do it in one line: 你可以在一行中完成:
print(all(map(lambda x:len(x)==2, my_list)))
First I map an on-fly function that check if the length is two. 首先,我映射一个动态函数,检查长度是否为2。 Then I apply all that returns True if all values are True, else False.
如果所有值都为True,则应用all返回True,否则返回False。
In production code, you could use assert 在生产代码中,您可以使用assert
assert all(map(lambda x:len(x)==2, my_list)), 'Not all have length 2'
Results: 结果:
Using all() and map() . 使用all()和map() 。 Mapping
len
with my_list
to find length of the sub-list
. 将
len
与my_list
映射以查找sub-list
长度。
my_list = [["obj1", "item1"], ["obj2", "item2", "item1"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
all(i == 2 for i in map(len, my_list))
Output: 输出:
False
If you want to check all the length is identical. 如果要检查所有长度是否相同。
my_list = [["obj1", "item1"], ["obj2", "item2"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
len(set(list(map(len, my_list)))) <=1
Output: 输出:
True
You can just run through your list of lengths and check what their lengths are. 您可以浏览您的长度列表并检查它们的长度。 If all the items in
lengths
are 2, then true otherwise false: 如果所有
lengths
为2的项目, lengths
true,否则为false:
my_list = [["obj1","item1"], ["obj2","item2", "red" ]]
lengths = [len(x) for x in my_lists]
allLensEqual = True
for I in lengths:
if I != 2:
allLensEqual = False
break
Alternatively, you could just use the any
function. 或者,您可以使用
any
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.