我有一個嵌套串列,形狀像
mylist = [[a, b, c, d], [e, f, g, h], [i, j, k, l]]
我需要拆分嵌套串列,以便每兩個專案像這樣分組在一起:
Nested_list = [[[a, b], [c, d], [[e, f], [g, h]], [[i, j], [k, l]]
我嘗試通過使用附加它們的for回圈將它們分開,但這不起作用。
uj5u.com熱心網友回復:
mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
nested_list = [ [i[:2], i[2:]] for i in mylist ]
print(nested_list)
輸出:
[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']], [['i', 'j'], ['k', 'l']]]
uj5u.com熱心網友回復:
mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
Nested_list = []
for x in mylist:
Nested_list.append(x[:2])
Nested_list.append(x[2:])
print(Nested_list)
輸出:[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j '], ['k', 'l']]
uj5u.com熱心網友回復:
import numpy as np
Nested_list = np.array(mylist).reshape(-1,2,2)
輸出:
array([[['a', 'b'],
['c', 'd']],
[['e', 'f'],
['g', 'h']],
[['i', 'j'],
['k', 'l']]], dtype='<U1')
uj5u.com熱心網友回復:
from itertools import *
my_list = chain.from_iterable(my_list)
def grouper(inputs, n):
iters = [iter(inputs)] * n
return zip_longest(*iters)
print(list(grouper(my_list, 2)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530219.html
上一篇:如何在字典中搜索/附加串列
