Python中如何將二維列表轉換成一維列表

from:https://www.cnblogs.com/huangbiquan/p/8025691.html

https://blog.csdn.net/cymy001/article/details/77881706

已知:a = [(4,2,3), (5, 9, 1), (7,8,9)]
希望將二維列表轉換成一維列表:["4,2,3", "5, 9, 1", "7,8,9"]

具體實現方法如下:

複製代碼

>>> a = [(4,2,3), (5, 9, 1), (7,8,9)]
>>> from itertools import chain
>>> list(chain.from_iterable(a))
[4, 2, 3, 5, 9, 1, 7, 8, 9]
>>> from tkinter import _flatten   # python2.7也可以from compiler.ast import flatten
>>> _flatten(a)
(4, 2, 3, 5, 9, 1, 7, 8, 9)

>>> [','.join(map(str,t)) for t in a]
['4,2,3', '5,9,1', '7,8,9']
>>> from itertools import starmap
>>> list(starmap('{},{},{}'.format,a))
['4,2,3', '5,9,1', '7,8,9']

#笨辦法,但是可以提供一種思路
a = [(4, 2, 3), (5,9,1), (7,8,9)]
i=0
while i<3:
    a[i]=str(a[i])[1:3*3-1]
    i=i+1
print (a[0:3])

>>> 
['4, 2, 3', '5, 9, 1', '7, 8, 9']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章