我正在尝试为此函数内的列表创建列表理解。我想知道是否可以让它更干净。
def load_list():
review_list = []
for counter, entry in enumerate(os.listdir('data/review')):
if os.path.isfile(os.path.join('data/review', entry)):
with open(f'data/review/{counter}.txt', encoding='utf-8') as fp:
review_list.append(fp.read().splitlines())
return review_list
假设
此行使用计数器:
with open(f'data/review/{counter}.txt', encoding='utf-8') as fp:
应该使用条目:
with open(f'data/review/{entry}.txt', encoding='utf-8') as fp:
然后我们可以使用 Walrus 运算符来简化原始代码并进行列表理解
原始代码中的海象运算符
import os
def load_list():
review_list = []
for entry in os.listdir('data/review'):
if os.path.isfile(file_path := os.path.join('data/review', entry)):
with open(file_path, encoding='utf-8') as fp:
review_list.append(fp.read().splitlines())
return review_list
重写为列表理解
from os import listdir
from os.path import isfile, join
def load_list():
return [open(file_path, encoding='utf-8').read().splitlines() for entry in listdir('data/review') if isfile(file_path := join('data/review', entry))]
依靠假设 3 来关闭列表理解中的文件。
我来这里寻找是否已经有标准实现,但这可以通过自定义内联来实现:
class With:
def __init__(self, ctx_mgr):
self._ctx_mgr = ctx_mgr
def do(self, fn):
with self._ctx_mgr as ctx:
return fn(ctx)
def load_list():
return [
With(open(file_path, encoding='utf-8')).do(lambda fh: fh.read().splitlines())
for entry in listdir('data/review')
if isfile(file_path := join('data/review', entry))
]
上面简单的
With
实现可以进一步扩展以同时处理多个上下文管理器。