python列表相邻两元素组成元组

demo = [1,2,3,4,5]
转换成
[(1,2),(3,4),(5,None)]

demo = [1]
转换成
[(1,None)]

成双的组合,单个的加None,为空时什么都不干
浮云间
浏览 1658回答 4
4回答

四季花海

print map(None, *([iter([1,2,3,4,5])] * 2))#[(1, 2), (3, 4), (5, None)]print map(None, *([iter([1])] * 2))#[(1, None)]

月关宝盒

list(dict(zip(demo[::2], demo[1::2] if len(demo)%2==0 else demo.append(None))).items())还是分2行吧 demo if len(demo)%2 == 0 else demo.append(None) list(dict(zip(demo[::2],demo[1::2])).items())

慕少森

demo = [1, 2, 3, 4, 5] print(map(None, demo[::2], demo[1::2]))

守候你守候我

python3 >>> from itertools import zip_longest as zipl >>> list(zipl(*([iter([1,2,3,4,5])] * 2))) [(1, 2), (3, 4), (5, None)] >>> list(zipl(*([iter([1])] * 2))) [(1, None)]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python