码迷,mamicode.com
首页 > 编程语言 > 详细

Python中如何将二维列表转换成一维列表

时间:2017-12-12 01:04:13      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:iterable   pos   ble   tool   rto   flat   color   方法   nbsp   

已知: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]

 

Python中如何将二维列表转换成一维列表

标签:iterable   pos   ble   tool   rto   flat   color   方法   nbsp   

原文地址:http://www.cnblogs.com/huangbiquan/p/8025691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!