liushuibufuqin 2017-12-12
Python中如何将二维列表转换成一维列表
已知: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']
之前提到去除一维数组中的重复元素用unique()函数,如果要去除二维数组中的重复行该怎么操作呢?list2=list必须先把列表中每个元素转化为tuple,因为list不可哈希但是tuple可哈希。