在列表中选择一定长度的列表

Selecting lists within a list that are of a certain length

这是我的:

original_list=[[1,2],[1,2,3],[1,2],[1,2,3,4],[1,2,3]]

我想在我的列表中找到长度为 2、3、4 等的列表:

length2_list=[[1,2],[1,2]]

length3_list=[[1,2,3],[1,2,3]]

length4_list=[[1,2,3,4]]

我该怎么做?

列出理解

#don't call lists "list" as a variable 
l=[[1,2],[1,2,3],[1,2],[1,2,3,4],[1,2,3]]

#for len 2
l_2=[x for x in l if len(x)==2]

#for len 3
l_3=[x for x in l if len(x)==3]

等等

Len()函数很简单,它可以告诉你列表的长度

origal_list=[[1,2],[1,2,3],[1,2],[1,2,3,4],[1,2,3]]

length2_list=[]

length3_list=[]

length4_list=[]


for lst in origal_list:
    if len(lst) == 2:
        length2_list.append(lst)
    if len(lst) == 3:
        length3_list.append(lst)
    if len(lst) == 4:
        length4_list.append(lst)

print(length2_list)
print(length3_list)
print(length4_list)

结果:

[[1, 2], [1, 2]]
[[1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 4]]

尝试这样的事情,它将适用于 n 个长度为 n 的列表:

lists = {}
list = [[1, 2], [1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3]]

for l in list:
    length = len(l)
    if lists.get(length) is None:
        lists[length] = []
    lists[length].append(l)

这将创建一个字典,该字典的长度将作为列表列表的键。然后它遍历原始列表并将其附加到正确的键。

它会输出这样的东西:{2: [[1, 2], [1, 2]], 3: [[1, 2, 3], [1, 2, 3]], 4: [[1, 2, 3, 4]]}