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设计】。

相关文章

python读取tif图片时保留其16bit的编码格式实例

tif图片的编码格式一般是16bit的,在使用python-opencv读取tif文件时,为了保留其编码格式,我们需要用以下的方式: import numpy as np impor...

Python通过PIL获取图片主要颜色并和颜色库进行对比的方法

本文实例讲述了Python通过PIL获取图片主要颜色并和颜色库进行对比的方法。分享给大家供大家参考。具体分析如下: 这段代码主要用来从图片提取其主要颜色,类似Goolge和Baidu的图...

Python 列表去重去除空字符的例子

如下所示: # x = ['c b a',"e d f"] # y = [] # for i in x: # for ii in i: # # print(ii) # if ii =...

postman传递当前时间戳实例详解

postman传递当前时间戳实例详解

请求动态参数(例如时间戳) 有时我们在请求接口时,需要带上当前时间戳这种动态参数,那么postman能不能自动的填充上呢。 我们可以使用postman的pre-request scrip...

Python微信库:itchat的用法详解

Python微信库:itchat的用法详解

在论坛上看到了用Python登录微信并实现自动签到,才了解到一个新的Python库: itchat 库文档说明链接在这:  itchat 我存个档在我网站(主要是我打...