有沒有辦法交替地展平嵌套串列的值?
例子:
nested_list = [[1, 3, 5], [2, 4]]
我的預期輸出是:
[1, 2, 3, 4, 5]
uj5u.com熱心網友回復:
使用hstack自numpy
import numpy as np
nested_list = [[1, 3, 5], [2, 4]]
new_nested_list = np.hstack(nested_list)
現在new_nested_list等于[1 3 5 2 4]
uj5u.com熱心網友回復:
您可以在沒有 numpy 的情況下使用迭代器來執行此操作,并在串列停止增長時進行跟蹤:
nested_list = [[1, 3, 5], [2, 4]]
# create a list of iterators per sublists
k = [iter(sublist) for sublist in nested_list]
# collect values
res = []
growing = True
# choose a value thats not inside your lists
sentinel = None
while growing:
growing = False
for i in k:
# returns sentinel gets None if sublist no longer iterable
u = next(i, sentinel)
# add if it got a value
if u != sentinel:
growing = True
res.append(u)
print(res) # [1,2,3,4,5]
如果None串列中有值,則需要選擇另一個sentinel值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425874.html
標籤:Python python-3.x 列表
