简体   繁体   English

Python使用子列表拆分列表

[英]Python Split a list with sublists

I have a problem with my list. 我的清单有问题。 I have a list with many sublist. 我有一个包含许多子列表的列表。 This looks like this: 看起来像这样:

L=[[1,5],[1,1,2,8,5,6],[6,46,35,86,24,3,34,46,23,35],[12,14,53,24,41,53],[1,3,6,4,3,8],[2,5,54,4,61,72,65,54],[43,6,2,6,51,3,43,13,64,52,5,8,3,57,52]]

What I want is something like this: 我想要的是这样的:

L1=[1,5]
L2=[1,1,2,8,5,6]
L3=[6,46,35,86,24,3,34,46,23,35]
L4=[12,14,53,24,41,53]
L5=[1,3,6,4,3,8]
...

I tried it with itertools.groupby() , but this just gave me : 我尝试了itertools.groupby() ,但这给了我:

L=[[[1,5],[1,1,2,8,5,6],[1,3,6,4,3,8]],[6,46,35,86,24,3,34,46,23,35],[12,14,53,24,41,53],[2,5,54,4,61,72,65,54],[43,6,2,6,51,3,43,13,64,52,5,8,3,57,52]]

How can I do what I want? 我该怎么办?

You don't need to create variables L1 , L2 , L3 , etc. List indexing already does what you need: 您不需要创建变量L1L2L3等。列表索引已经可以满足您的需要:

L=[[1,5],
   [1,1,2,8,5,6],
   [6,46,35,86,24,3,34,46,23,35],
   [12,14,53,24,41,53],
   [1,3,6,4,3,8],
   [2,5,54,4,61,72,65,54],
   [43,6,2,6,51,3,43,13,64,52,5,8,3,57,52]]

print L[0]  # prints [1, 5]
print L[4]  # prints [1, 3, 6, 4, 3, 8]

# If you want the first element of the first list in L, you use
L[0][0]

This has the advantage of working regardless of the size of L . 无论L的大小如何,这都有工作的优势。 You don't need to make a zillion variables if L is huge, or rewrite your program for every possible size of L. 如果L很大,则无需制作大量的变量,也不必为L的每个可能的大小重写程序。

best I can do for you - create a dict with keys like L1, L2: 我能为您做的最好的-用L1,L2之类的键创建字典:

>>> {'L{}'.format(i): x for i, x in enumerate(L, 1)}
{'L1': [1, 5],
 'L2': [1, 1, 2, 8, 5, 6],
 'L3': [6, 46, 35, 86, 24, 3, 34, 46, 23, 35],
 'L4': [12, 14, 53, 24, 41, 53],
 'L5': [1, 3, 6, 4, 3, 8],
 'L6': [2, 5, 54, 4, 61, 72, 65, 54],
 'L7': [43, 6, 2, 6, 51, 3, 43, 13, 64, 52, 5, 8, 3, 57, 52]}

Firstly, itertools.groupby() won't help you here. 首先, itertools.groupby()在这里无济于事。

You can use unpacking here, a fantastic feature in python (in my opinion): 您可以在此处使用解压缩功能,这是python中的一个很棒的功能(我认为):

L1, L2, L3, L4, L5, L6, L7 = L

But if you're intending to have something like this, then you're looking at the wrong approach. 但是,如果您打算拥有这样的东西,那么您正在寻找错误的方法。 Consider a dictionary: 考虑一个字典:

d = {}
for i, j in enumerate(L, 1):
    d['L{}'.format(i)] = j

Printing d gives: 打印d得到:

{'L6': [2, 5, 54, 4, 61, 72, 65, 54], 'L7': [43, 6, 2, 6, 51, 3, 43, 13, 64, 52, 5, 8, 3, 57, 52], 'L4': [12, 14, 53, 24, 41, 53], 'L5': [1, 3, 6, 4, 3, 8], 'L2': [1, 1, 2, 8, 5, 6], 'L3': [6, 46, 35, 86, 24, 3, 34, 46, 23, 35], 'L1': [1, 5]}

You can use indexes!! 您可以使用索引!

 L1=L[0]
 L2=L[1]

and so on.... 等等....

 print L1
 >> [1,5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM