我正在尝试创建一个列表,其中包含在双引号中找到的所有字符串,到目前为止,我已经知道了。
matches = ['8 "app/Http/Controllers/Controller.php" line 1', '9 "app/Http/Controllers/PostController.php" line 1']
if len(matches) > 1:
for match in matches:
matches = re.findall(r'\"(.+?)\"', match)
print(matches[0])
它输出此
app/Http/Controllers/Controller.php
app/Http/Controllers/PostController.php
我想将这些字符串变成一个列表,这样看起来
['app/Http/Controllers/Controller.php','app/Http/Controllers/PostController.php']
它也应该是动态的,因为双引号内可以有两个以上的字符串。
这怎么办?
答案 0 :(得分:3)
您可以将print
语句用append
替换为循环之前初始化的列表。
import re
matches = ['8 "app/Http/Controllers/Controller.php" line 1', '9 "app/Http/Controllers/PostController.php" line 1']
output = []
if len(matches) > 1:
for match in matches:
matches = re.findall(r'\"(.+?)\"', match)
output.append(matches[0])
print(output)
这将输出:
['app/Http/Controllers/Controller.php', 'app/Http/Controllers/PostController.php']
答案 1 :(得分:1)
您可以使用list comprehension来更简洁地生成列表。
在python中,列表推导允许`[x for x in(1,4,3,2)]格式。
所以这将导致这段代码。
import re
matches = ['8 "app/Http/Controllers/Controller.php" line 1', '9 "app/Http/Controllers/PostController.php" line 1']
results = [re.findall(r'\"(.+?)\"', match)[0] for match in matches]
结果变量将为:
['app/Http/Controllers/Controller.php', 'app/Http/Controllers/PostController.php']