什么类型的循环是 [i for i in x for i! =0] 在 python 中?
what type of loops are [i for i in x for i! =0] in python?
假设我有一个列表:
c = ['A','B','C','']
我循环遍历它以使用以下代码在没有空元素 '' 的情况下打印:
for i in c:
if i != '':
print(i)
i = i
else:
pass
outputs:
A
B
C
我也可以使用:
[i for i in x for i!=0]
outputs:
['A',
'B',
'C']
我的问题是下面这种类型的循环叫什么?
如何在此循环中添加 if else 语句?以及任何可以帮助我了解更多信息的 material。
这叫做列表理解。
你可以通过if条件得到想要的list(d)如下
c = ['A','B','C','']
d = [i for i in c if i!= '']
这叫做列表理解。
if 语句有两种实现方式:
>>> a = [5, 10, 15, 20, 25, 30, 35]
>>> b = [i for i in a if i % 3 == 0]
>>> b
... [15, 30]
>>> c = [i if i % 3 == 0 else 0 for i in a]
>>> c
... [0, 0, 15, 0, 0, 30, 0]
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
在 python 文档中找到更多关于列表理解的信息 link:
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
假设我有一个列表:
c = ['A','B','C','']
我循环遍历它以使用以下代码在没有空元素 '' 的情况下打印:
for i in c:
if i != '':
print(i)
i = i
else:
pass
outputs:
A
B
C
我也可以使用:
[i for i in x for i!=0]
outputs:
['A',
'B',
'C']
我的问题是下面这种类型的循环叫什么? 如何在此循环中添加 if else 语句?以及任何可以帮助我了解更多信息的 material。
这叫做列表理解。
你可以通过if条件得到想要的list(d)如下
c = ['A','B','C','']
d = [i for i in c if i!= '']
这叫做列表理解。
if 语句有两种实现方式:
>>> a = [5, 10, 15, 20, 25, 30, 35]
>>> b = [i for i in a if i % 3 == 0]
>>> b
... [15, 30]
>>> c = [i if i % 3 == 0 else 0 for i in a]
>>> c
... [0, 0, 15, 0, 0, 30, 0]
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
在 python 文档中找到更多关于列表理解的信息 link:
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions