本文介绍了如何在python中简化两个嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试简化python中两个必需的for循环,但是我无法解决此问题.我的代码:

I'm trying to simplify two neested for loops in python but I cant resolve this.My code:

head = [[1, 2], [3, 4]]
temp = []
for array in head:
    for element in array:
        temp.append(element)
print(temp)
========OUTPUT========
[1, 2, 3, 4]

我尝试:

head = [[1, 2], [3, 4]]
temp = []
for array in head:
   temp += [element for element in array]
print(temp)

但是只能简化一个循环

@serafeim针对我的情况的特定解决方案:

Specific solution for my case by @serafeim:

head = [[1, 2], [3, 4]]
print([element for array in head for element in array])

其他解决方案:

通过肛门

Other solutions:

By anon

from functools import reduce
head = [[1, 2], [3, 4]]
print(reduce(list.__add__, head))

通过:@chepner

By: @chepner

from itertools import chain
head = [[1, 2], [3, 4]]
print([x for x in chain.from_iterable(head)])

通过:@ R-zu

import numpy as np
head = [[1, 2], [3, 4]]
print(np.array(head).reshape(-1).tolist())

推荐答案

这已经可以从itertools模块中获得.

This is already available from the itertools module.

from itertools import chain

temp = [x for x in chain.from_iterable(head)]
# or just temp = list(chain.from_iterable(head))

这篇关于如何在python中简化两个嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:12