简体   繁体   English

如何截断列表列表中的每个列表?

[英]How to truncate each list in a list of lists?

I have a list of lists, and in each list I want to truncate all values after the first two.我有一个列表列表,在每个列表中我想截断前两个之后的所有值。

Here is an example with my attempt这是我尝试的一个例子

listss = [ [ 2, 4, 5, 7 ,7], [4, 5,], [2,4 ,4 ,4,4,7,9]]

for item in listss:
    item = item[0:2]

However, this does not alter any of the lists.但是,这不会改变任何列表。

The desired result should look like期望的结果应该是这样的

[ [ 2, 4], [4, 5], [2,4]]

You could do:你可以这样做:

listss = [[2, 4, 5, 7, 7], [4, 5, ], [2, 4, 4, 4, 4, 7, 9]]

for i, item in enumerate(listss):
    listss[i] = item[:2]

print(listss)

You can delete slices in the sub-lists in-place:您可以就地删除子列表中的切片:

for item in listss:
    del item[2:]

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

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