python实现将读入的多维list转为一维list的方法
第一种:使用extend()
>>> lines = open('test.txt').readlines() >>> lines ['1\n', '2\n', '3\n', '4,5\n'] >>> for line in lines: ... ll.extend(line.strip().split(',')) ... >>> ll ['1', '2', '3', '4', '5']
第二种:使用+
>>> ll = [] >>> lines = open('test.txt').readlines() >>> lines ['1\n', '2\n', '3\n', '4,5\n'] >>> for line in lines: ... ll = ll + line.strip().split(',') ... >>> ll ['1', '2', '3', '4', '5']
第三种:使用flat array数组的自带方法
>>> ll = [] >>> lines = open('test.txt').readlines() >>> for line in lines: ... ll.append(line.strip().split(',')) ... >>> ll = np.array(ll) >>> np.hstack(ll.flat) array(['1', '2', '3', '4', '5'], dtype='|S1') >>> list(np.hstack(ll.flat)) ['1', '2', '3', '4', '5']
总结:
1. extend()与append()的区别
append()可以接受任何数据类型和格式的数据作为一个元素插入原list
extend() 则仅能将任何数据类型和格式的数据展开作为一组元素插入原list
eg.
>>> a = [1,'a'] >>> a.extend(np.array([2,'b'])) >>> a [1, 'a', '2', 'b'] >>> a.extend([3,['c']]) >>> a [1, 'a', '2', 'b', 3, ['c']] >>> a = [1,'a'] >>> a.extend(np.array([2,'b'])) >>> a [1, 'a', '2', 'b'] >>> a.extend([3,['c']]) >>> a [1, 'a', '2', 'b', 3, ['c']] >>> a = [1,'a'] >>> a.append(np.array([2,'b'])) >>> a [1, 'a', array(['2', 'b'], dtype='|S21')] >>> a.append([3,['c']]) >>> a [1, 'a', array(['2', 'b'], dtype='|S21'), [3, ['c']]]
2. flatten()无法对dtype = object的array进行展开,dtype = object说明array中的元素是list,即其不是满矩阵结构
eg.
>>> a = np.array([[1,2],[3,4]]) >>> a.dtype dtype('int64') >>> a.flatten() array([1, 2, 3, 4]) >>> >>> a = np.array([[1,2],[3,4],[5]]) >>> a.flatten() array([[1, 2], [3, 4], [5]], dtype=object)
3.readlines读取文件默认str,可以通过map转换数据类型
eg.
>>> ll = [] >>> lines = open('test.txt').readlines() >>> lines ['1\n', '2\n', '3\n', '4,5\n'] >>> for line in lines: ... ll.append(map(int,line.strip().split(','))) ... >>> ll [[1], [2], [3], [4, 5]]
以上这篇python实现将读入的多维list转为一维list的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。