简体   繁体   English

如何将列表列表的后半部分作为列表列表?

[英]How to get the second half of a list of lists as a list of lists?

So I know that to get a single column, I'd have to write 所以我知道要得到一列,我必须写

a = list(zip(*f)[0])

and the resulting a will be a list containing the first element in the lists in f. 结果a将是一个包含f中列表中第一个元素的列表。

How do I do this to get more than one element per list? 如何执行此操作以使每个列表包含多个元素? I tried 我试过了

a = list(zip(*f)[1:19])

But it just returned a list of lists where the inner list is the composed of the ith element in every list. 但是它只是返回了一个列表列表,其中内部列表由每个列表中的ith元素组成。

The easy way is not to use zip() . 最简单的方法是不使用zip() Instead, use a list comprehension : 相反,请使用列表推导

a = [sub[1:19] for sub in f]

If it is actually the second half that you are looking for: 如果实际上是您要查找的下半部分:

a = [sub[len(sub) // 2:] for sub in f]

That will include the 3 in [1, 2, 3, 4, 5] . 这将包括3[1, 2, 3, 4, 5] If you don't want to include it: 如果您不想包含它:

a = [sub[(len(sub) + 1) // 2:] for sub in f]

You should definitely prefer @zondo's solution for both performance and readability. 对于性能和可读性,您绝对应该首选@zondo的解决方案。 However, a zip based solution is possible and would look as follows (in Python 2): 但是,可以使用基于zip的解决方案,其外观如下所示(在Python 2中):

zip(*zip(*f)[1:19])

You should not consider this cycle of unpacking, zipping, slicing, unpacking and re-zipping in any serious code though ;) 不过,您不应该考虑使用任何严肃的代码来进行解压缩,压缩,切片,解压缩和重新压缩的循环;)

In Python 3, you would have to cast both zip results to list , making this even less sexy. 在Python 3中,您必须将两个zip结果都ziplist ,从而使其更加性感。

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

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