你会如何解释Python中的for循环和列表推导式?
列表推导式提供了一种基于现有列表创建列表的简洁方式。 使用列表推导式时,可以利用任何可迭代的对象来建立列表,包括字符串和元组。 列表推导式包含一个包含表达式的可迭代对象,后跟一个for子句。 这可以后跟其他for或if子句。
让我们看一个以字符串为基础创建列表的示例:
hello_letters = [letter for letter in 'hello']
print(hello_letters)
这会输出:
['h', 'e', 'l', 'l', 'o']
字符串“hello”是可迭代的,每次循环迭代时,“letter”都被分配一个新值。 这个列表推导式等同于:
hello_letters = []
for letter in 'hello':
hello_letters.append(letter)
您也可以在推导式上放置条件。 例如,
hello_letters = [letter for letter in 'hello' if letter!='l']
print(hello_letters)
这会输出:
['h', 'e', 'o']
您可以对变量执行各种操作。 例如,
squares = [i ** 2 for i in range(1, 6)]
print(squares)
这会输出:
[1, 4, 9, 16, 25]
这些推导式有很多用例。它们非常表达和有用。 您可以在以下网址上了解更多信息: https://www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3.
更多Python相关文章,请阅读:Python 教程
极客教程