Turning a list into nested lists in python

2019-01-09 07:00发布

Possible Duplicate:
How can I turn a list into an array in python?

How can I turn a list such as:

data_list = [0,1,2,3,4,5,6,7,8]

into a list of lists such as:

new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]

ie I want to group ordered elements in a list and keep them in an ordered list. How can I do this?

Thanks

6条回答
可以哭但决不认输i
2楼-- · 2019-01-09 07:01

This groups each 3 elements in the order they appear:

new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)]

Give us a better example if it is not what you want.

查看更多
倾城 Initia
3楼-- · 2019-01-09 07:01

new_list = [data_list[x:x+3] for x in range(0, len(data_list) - 2, 3)]

List comprehensions for the win :)

查看更多
倾城 Initia
4楼-- · 2019-01-09 07:03

Something like:

map (lambda x: data_list[3*x:(x+1)*3], range (3))
查看更多
叛逆
5楼-- · 2019-01-09 07:10

Do you have any sort of selection criteria from your original list?

Python does allow you to do this:

new_list = []
new_list.append(data_list[:3])
new_list.append(data_list[3:6])
new_list.append(data_list[6:])

print new_list
# Output:  [ [0,1,2] , [3,4,5] , [6,7,8] ]
查看更多
聊天终结者
6楼-- · 2019-01-09 07:18

Based on the answer from Fred Foo, if you're already using numpy, you may use reshape to get a 2d array without copying the data:

import numpy
new_list = numpy.array(data_list).reshape(-1, 3)
查看更多
疯言疯语
7楼-- · 2019-01-09 07:26

This assumes that data_list has a length that is a multiple of three

i=0
new_list=[]
while i<len(data_list):
  new_list.append(data_list[i:i+3])
  i+=3
查看更多
登录 后发表回答