玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python2版本列表推导二维数组问题求助

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = [x for x in i for i in a]
>>> b
[1, 1, 2, 2, 3, 3]
>>> c = [x for x in i for i in a] 
>>> c
[4, 4, 5, 5, 6, 6]
  1. 如何解释上面代码的运行结果?
    一般的得到的结果是[4, 4, 5, 5, 6, 6],但是偶然会得到[1, 1, 2, 2, 3, 3],这是为什么呢?

  2. 如何把[[1, 2, 3], [4, 5, 6]]用列表推导成[1,2,3,4,5,6]的形式?

In [5]: b = [x for i in a for x in i]

In [6]: b
Out[6]: [1, 2, 3, 4, 5, 6]

三维的
In [7]: aa = [[[1], [2], [3]], [[4], [5], [6]]]
In [8]: b = [y for i in aa for x in i for y in x]

In [9]: b
Out[9]: [1, 2, 3, 4, 5, 6]

a = [[1, 2, 3], [4, 5, 6]]
all = []
for i in a:
    all += i

没想到更简洁的方法。

b = [x for x in i for i in a] 在我的解释器中无法运行.

>>> b = [item for sublist in a for item in sublist]
>>> b
[1, 2, 3, 4, 5, 6]

flattenstack overflow 上有详细的讨论, 上面的方法被发现是最快的,

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd18591.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月31日 - 14时35分23秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules