python实现把二维列表变为一维列表的方法分析

yipeiwu_com7年前Python基础

本文实例讲述了python实现把二维列表变为一维列表的方法。分享给大家供大家参考,具体如下:

c = [[1,2,3], [4,5,6], [7,8,9]]

1.用列表推导式

>>> [n for a in c for n in a ]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.用嵌套循环展开

>>> result=[]
>>> for a in c:
 for n in a:
 result.append(n)
 result  #result的位置没有和第一个for对齐,所以结果不理想
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

3.用sum对列表的求和

>>> sum(c,[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

4.导入相关的包

>>>from itertools import chain
>>>list(chain(*vec))
[1,2, 3, 4, 5, 6, 7, 8, 9]
>>>from itertools import chain
>>>list(chain(*vec))
[1,2, 3, 4, 5, 6, 7, 8, 9]

更多关于Python相关内容可查看本站专题:《Python列表(list)操作技巧总结》、《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Django中几种重定向方法

这里使用的是django1.5 需求: 有一个界面A,其中有一个form B, 前台提交B之后,后台保存数据之后,返回界面A,如果保存失败需要在A界面提示错误。 这里就需要后台的重定向,...

TensorFlow绘制loss/accuracy曲线的实例

TensorFlow绘制loss/accuracy曲线的实例

1. 多曲线 1.1 使用pyplot方式 import numpy as np import matplotlib.pyplot as plt x = np.arange(1,...

python实现数通设备tftp备份配置文件示例

  环境:【wind2003[open Tftp server] + virtualbox:ubuntn10 server】tftp : Open TFTP Server&nb...

python threading模块操作多线程介绍

python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。thread是比较底层的模块,threading是对thread做了一...

python ip正则式

ip正则式为:r'(([12][0-9][0-9]|[1-9][0-9]|[1-9])\.){3,3}([12][0-9][0-9]|[1-9][0-9]|[1-9])' 以下为一个示例...