简体   繁体   English

如何将列表理解转换为普通的 for 循环?

[英]How can I convert a list comprehension to a normal for loop?

I'm trying to learn how I can convert Python list comprehensions to a normal for-loop.我正在尝试学习如何将 Python 列表理解转换为普通的 for 循环。 I have been trying to understand it from the pages on the net, however when I'm trying myself, I can't seem to get it to work.我一直试图从网上的页面上理解它,但是当我自己尝试时,我似乎无法让它发挥作用。

What I am trying to convert is the following:我要转换的内容如下:
1: 1:

n, m = [int(i) for i in inp_lst[0].split()]

and this one (which is a little bit harder):而这个(有点难):
2: 2:

lst = [[int(x) for x in lst] for lst in nested[1:]]

However, I am having no luck with it.但是,我没有运气。

What I have tried:我试过的:
1: 1:

n = []
for i in inp_lst[0].split():
    n.append(int(i))
print(n)

If I can get some help, I will really appreciate it:D如果我能得到一些帮助,我将非常感激:D

Generally speaking, a list comprehension like:一般来说,列表理解如下:

a = [b(c) for c in d]

Can be written using a for loop as:可以使用 for 循环编写为:

a = []
for c in d:
    a.append(b(c))

Something like:就像是:

a, b = [c(d) for d in e]

Might be generalized to:可以概括为:

temp = []
for d in e:
    temp.append(c(d))

a, b = temp

Something like:就像是:

lst = [[int(x) for x in lst] for lst in nested[1:]]

Is no different.没有什么不同。

lst = []
for inner_lst in nested[1:]:
    lst.append([int(x) for x in inner_lst])

If we expand that inner list comprehension:如果我们扩展该内部列表理解:

lst = []
for inner_lst in nested[1:]:
    temp = []
    for x in inner_lst:
        temp.append(int(x))
    lst.append(temp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM