Python列表理解

时间:2020-02-23 14:42:53  来源:igfitidea点击:

在上一教程中,我们了解了Python排序列表。
在本教程中,我们将学习Python列表理解。

Python列表理解

基本上,Python列表理解是在大多数语言中并不常见的想法。
它基本上用于生成具有某些特定属性的元素列表。
而且,Python List Comprehension使代码更小但更有效。
让我们考虑以下代码。

word = "Python"
letters = []

for letter in word:
  letters.append(letter)

print(letters)

您将获得输出为

['P', 'y', 't', 'h', 'o', 'n']

但是您可以通过Python List Comprehension缩短前面的代码。
所以所需的代码将是

word = "Python"

# shorten the code
letters = [letter for letter in word]
print(letters)

你会得到相同的输出

['P', 'y', 't', 'h', 'o', 'n']

Python列表理解的基本结构

基本结构由三个参数组成。
基于这三个参数,python生成了一个新列表。
参数在下面的列表中给出

  • 变量
  • 输出表达式
  • 参考序列
  • 谓词(可选)

在本节中,我们将学习如何使用Python List Comprehension进行编码。
假设您有一个数字列表。
现在,您要创建一个新列表,其中仅存在上一个列表的偶数的立即数。
所以传统的代码将是

reference = [1, 2, 3, 4, 5, 6]

output = []

for number in reference:
  if number % 2 == 0:
      # the number is even
      prev_num = number-1  # calculate previous number
      output.append(prev_num)  # append to the list

print(output)

以下代码的输出将是

[1, 3, 5]

相当大的代码,对不对?但是,如果您使用Python List Comprehension,则代码会很短。
代码将是

reference = [1, 2, 3, 4, 5, 6]

output = [(number-1) for number in reference if number % 2 == 0]

print(output)

如前所述,Python List Comprehension具有三个参数。
在前面的代码中,我们还使用了所有参数。
请参见下图。
为了更好地理解,每个参数的颜色都不同

因此,这就是编写Python List Comprehension的结构!

用于字符串

到目前为止,我们已经看到了使用数字的Python列表推导示例。
您可以使用Python List Comprehension对String进行出色的处理。
假设您有一个字符串列表。
您想做一些修改,例如

  • 如果字符串是句子,请将其拆分为单词
  • 区分所有单词,例如:首字母大写,其余字母小

以下代码将帮助您理解。

list_string = ['maNgo', 'BanAna', 'PytHoN iS Love', 'Cat iS not doG']

# make the list of string to list of list of words
list_of_list = [sentence.split() for sentence in list_string]
print(list_of_list)

words = sum(list_of_list, [])  # make the list of list to a single list
print(words)  # print the list of word

# modify the case
correct_case = [str.upper(word[0])+str.lower(word[1:]) for word in words if len(word) > 1]

# print the list of word with desired case
print(correct_case)

因此,代码的输出将是

[['maNgo'], ['BanAna'], ['PytHoN', 'iS', 'Love'], ['Cat', 'iS', 'not', 'doG']]
['maNgo', 'BanAna', 'PytHoN', 'iS', 'Love', 'Cat', 'iS', 'not', 'doG']
['Mango', 'Banana', 'Python', 'Is', 'Love', 'Cat', 'Is', 'Not', 'Dog']

嵌套列表理解

但是,您也可以使用嵌套列表推导。
这意味着,您可以在另一个列表推导中使用列表推导。
例如,可以使用嵌套的Python列表Comprehension将前面的示例代码写得更短。
像这样,

list_string = ['maNgo', 'BanAna', 'PytHoN iS Love', 'Cat iS not doG']

correct_case = [str.upper(word[0])+str.lower(word[1:])
              for word in sum([sentence.split() for sentence in list_string], [])
              if len(word) > 1]

# print the list of word with desired case
print(correct_case)

输出将是

['Mango', 'Banana', 'Python', 'Is', 'Love', 'Cat', 'Is', 'Not', 'Dog']

但是以下代码在许多情况下不容易阅读。
因此,不建议在每种情况下都使用嵌套的Python List Comprehension,尽管它会使代码简短。