简体   繁体   English

Python在列表列表中组合项目

[英]Python combining items in a list of lists python

I have three items in a list of lists: 我在列表列表中有三个项目:

test = [[a,b,c],[d,e,f],[g,h,i]]

I want it to look like this: 我希望它看起来像这样:

test = [[a,b,c,d,e,f],[g,h,i]]

what is the best way to do this in python? 在python中执行此操作的最佳方法是什么?

Thanks for the help 谢谢您的帮助

>>> test = [[1,2,3], [4,5,6], [7,8,9]]
>>> test[0].extend(test.pop(1))  # OR  test[0] += test.pop(1)
>>> test
[[1, 2, 3, 4, 5, 6], [7, 8, 9]]
test = [test[0] + test[1], test[2]]

If you want to flatten of an arbitrary slice, use a slice assignment and a list comprehension on the part you want to flatten. 如果要展平任意切片,请在要展平的零件上使用切片分配和列表推导。

This flatten from position n to end of the list: 这从位置n变平到列表的末尾:

>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> n=2
>>> test[n:]=[[i for s in test[n:] for i in s]]
>>> test
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15]]

This flattens up to n (but including n ): 这将展平到n (但包括n ):

>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> test[0:n]=[[i for s in test[0:n] for i in s]]
>>> test
[[1, 2, 3, 4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]

This flattens in the middle (from and including n to include the additional groups specified): 这在中间变平(从n包括n以包括指定的其他组):

>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> test[n:n+2]=[[i for s in test[n:n+2] for i in s]]
>>> test
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15]]

Flatten all the sublists: 展平所有子列表:

>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> n=len(test)
>>> test[0:n]=[[i for s in test[0:n] for i in s]]
>>> test
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]

Note that in each case the slice on the assignment side is the same as the slice on the list comprehension side. 请注意,在每种情况下,分配侧的分片都与列表理解侧的分片相同。 This allows the use of the same slice object for each. 这允许为每个对象使用相同的切片对象

For the last case of flattening the whole list, obviously, you can just do test=[[i for s in test for i in s]] but the fact the logic is consistent allows you to wrap this in a function use a slice object. 显然,对于将整个列表弄平的最后一种情况,您可以执行test=[[i for s in test for i in s]]但是逻辑上一致的事实使您可以使用slice对象将其包装在函数中。

You could combine the first two items in the list of list with the + operator and you should use '' for your strings 您可以使用+运算符将列表列表中的前两项组合在一起,并且应该在字符串中使用''

test = [['a','b','c'],['e','f','g'],['h','i','j']]
result = [test[0] + test[1], test[2]]
print result

output:
[['a', 'b', 'c', 'e', 'f', 'g'], ['h', 'i', 'j']]

Using the more_itertools package: 使用more_itertools软件包:

import more_itertools as mit

list(mit.chunked(mit.flatten(test), 6))
# [[1, 2, 3, 4, 5, 6], [7, 8, 9]]

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

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