在python中使用for循环创建列表

时间:2019-02-08 14:13:42

标签: python python-3.x

我有一个关于在python中创建列表的问题。在我的代码中是#3。 我知道如何建立像

这样的列表
my_list = [88, "Peter", 3.4]

我也知道for循环的工作原理

names = ["ash", "John", "Kai"]
for x in names:
  print(x) 

但是我不明白这行代码的作用。似乎将列表的创建与for循环混合在一起:

sentences = [match[0] for match in matches]

如果是这样,那就很清楚了。

for match in matches:
    print(match[0])

示例代码

import re

some_sentences = 'Lorem ipsum dolor sit amet, duo delectus legendos 
reprimique ne, ad per cetero interpretaris, eu ius facete laoreet 
definitiones. In mei amet eruditi, ut sit vidit singulis atomorum. 
Nominavi suscipit his in, cu idque aliquid rationibus qui, te sed etiam 
apeirian reprehendunt. Electram posidonium nam eu, ei pri mollis 
referrentur, cu vel ludus maiorum philosophia.'

#1 create regex pattern
regex = re.compile('(.*?\.)(\s|$)')
#2 find all matches
matches = regex.findall(some_sentences)
#3 create a list
sentences = [match[0] for match in matches]
#4 print sentences
print(sentences)

0 个答案:

没有答案