python—使嵌套列表的每个元素都成为一个列表

pb3skfrl  于 2021-07-13  发布在  Java
关注(0)|答案(6)|浏览(380)

我有一个嵌套列表,上面写着:

lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]

我希望输出结果是:

new_list = [[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]

这是我的想法,但我认为它是输出一个平面,列表列表。

new_lst = []
for i in lst:
  i = list(i)
  for el in i:
    new_list.append([el])
print(new_lst)

我想在lst中保持每个预定义列表的长度

l7wslrjt

l7wslrjt1#

您可以使用列表理解并将每个元素附加到另一个列表中。

lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]
new = [[[numbers] for numbers in elements] for elements in lst]

上面的示例根据您想要的输出进行调整。

[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
vql8enpb

vql8enpb2#

尝试列表理解 [[ [e] for e in l] for l in lst]

6yjfywim

6yjfywim3#

你可以使用numpy的重塑 np.reshape ```

import numpy as np

lst = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6]])
lst
array([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]])

lst.shape
(3, 4)

lst.reshape(3,4,1)
array([[[1],
[2],
[3],
[4]],

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

   [[3],
    [4],
    [5],
    [6]]])

lst.reshape(3,4,1).tolist()
[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]

yks3o0rb

yks3o0rb4#

另一个版本,使用递归(您可以在输入中具有更高的深度):

lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]

def split(i):
    if isinstance(i, list):
        return [split(v) for v in i]
    else:
        return [i]

print(split(lst))

印刷品:

[[[1], [2], [3], [4]], [[2], [3], [4], [5]], [[3], [4], [5], [6]]]
bqucvtff

bqucvtff5#

您可以使用helper函数来更灵活地划分较小的列表。根据这里的答案。

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
             for i in range(wanted_parts) ]

lst = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]

ret =[]
for mini_list in lst:
    ret.append(split_list(mini_list, len(mini_list)))
cld4siwp

cld4siwp6#

我认为你使用多重for循环的想法是对的。这应该起作用:

list = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]

for i in range(0, 3):
     for j in range(0, 4):
          (list[i])[j] = [(list[i])[j]]

相关问题