python实现将读入的多维list转为一维list的方法

yipeiwu_com6年前Python基础

第一种:使用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设计】。

相关文章

20招让你的Python飞起来!

今天分享的这篇文章,文字不多,代码为主。绝对干货,童叟无欺,主要分享了提升 Python 性能的 20 个技巧,教你如何告别慢Python。原文作者 开元,全栈程序员,使用 Python...

Python使用Slider组件实现调整曲线参数功能示例

Python使用Slider组件实现调整曲线参数功能示例

本文实例讲述了Python使用Slider组件实现调整曲线参数功能。分享给大家供大家参考,具体如下: 一 代码 import numpy as np import matplotli...

详解Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码数

hasattr()函数 hasattr()函数用于判断是否包含对应的属性 语法: hasattr(object,name) 参数: object--对象 name--字符串,属性名 返回...

浅析Python的web.py框架中url的设定方法

浅析Python的web.py框架中url的设定方法

网页中的数据在传递的时候有GET和POST两种方式,GET是以网址的形式传参数,在web.py中有着很好的匹配,如果我们配置以下的urls urls =( '/','inde...

Python实现的网页截图功能【PyQt4与selenium组件】

本文实例讲述了Python实现的网页截图功能。分享给大家供大家参考,具体如下: 方法一、使用PyQt4的QtWebKit组件 #!/usr/bin/env python # -*-...