如何使用分隔符連接列表列表。如何在Python中使用分隔符連接列表列表
例如
in:
list:
[[1,2], [3,4,5], [6,7]]
with separator:
0
result:
[1, 2, 0, 3, 4, 5, 0, 6, 7]
如何使用分隔符連接列表列表。如何在Python中使用分隔符連接列表列表
in:
list:
[[1,2], [3,4,5], [6,7]]
with separator:
0
result:
[1, 2, 0, 3, 4, 5, 0, 6, 7]
例如您的列表存儲在x
:
x=[[1,2], [3,4,5], [6,7]]
只需使用reduce
與lambda函數:
y=reduce(lambda a,b:a+[0]+b,x)
現在y
是
[1, 2, 0, 3, 4, 5, 0, 6, 7]
或者你可以定義一個生成器功能:
def chainwithseperator(lis,sep):
it=iter(lis)
for item in it.next():
yield item
for sublis in it:
yield sep
for item in sublis:
yield item
現在呼籲:
y=list(chainwithseperator(x,0))
會帶給你不一樣的結果
這是以二次方式運行的時間,因爲列表的'+'在參數大小的總和中以時間線性運行。 – user2357112
我用'x = [[1,2]]''運行'[1,2,0]'是正確的結果,我不相信......與'x = [[1,2],[3,4,5]]相同' –
@JonClements你是對的我解決了發生器中的問題,但它使得它更復雜一點 – Lee
這是我會怎麼做:
l = [[1,2], [3,4,5], [6,7]]
result = [number for sublist in l for number in sublist+[0]][:-1]
最後的[:-1]
是刪除最後一個是0
的項目。
您可以使用Python列表使用extend()方法:
orig_list = [[1,2], [3,4,5], [6,7]]
out_list = []
for i in orig_list:
out_list.extend(i + [0])
# To remove the last element '0'.
print my_list[:-1]
可以tee
的list
視爲可迭代,只產生分離時,有一個以下項目。在這裏我們定義了一個名爲joinlist
功能包含發電機輔助函數來獲得相應的元素,然後返回使用chain.from_iterable
所有這些元素的扁平列表:
from itertools import tee, chain
def joinlist(iterable, sep):
def _yielder(iterable):
fst, snd = tee(iterable)
next(snd, [])
while True:
yield next(fst)
if next(snd, None):
yield [sep]
return list(chain.from_iterable(_yielder(iterable)))
重要的是要注意重要的是終止了while True:
發生在yield next(fst)
,因爲這會在某個時間點產生StopIteration
並導致發生器退出。
例:
x = [[1,2]]
y = [[1, 2], [3,4,5]]
z = [[1, 2], [3,4,5], [6, 7]]
for item in (x, y, z):
print item, '->', joinlist(item, 0)
# [[1, 2]] -> [1, 2]
# [[1, 2], [3, 4, 5]] -> [1, 2, 0, 3, 4, 5]
# [[1, 2], [3, 4, 5], [6, 7]] -> [1, 2, 0, 3, 4, 5, 0, 6, 7]
爲什麼隔板在第一和最後一個在最後結束使用? – thefourtheye
'separator'.join([str(x)for x in [list])。你期待什麼結果?字符串或列表 – simar
@thefourtheye:它幾乎與'str.join'一樣的行爲。 – user2357112