选择列表中具有一定长度的列表

问题描述 投票:0回答:3

这就是我所拥有的:

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]]

我怎么能这样做?

python python-3.x nested-lists
3个回答
2
投票

列表理解

#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]

等等


1
投票

使用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]]

0
投票

尝试这样的东西,它将适用于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]]}

© www.soinside.com 2019 - 2024. All rights reserved.