Python inline for if : 有更好的写法吗?
Python inline for if : Is there a better way to write this?
在用 Python 编写一些网络爬虫代码时,我的需求是这样的:
vals = [x.get_text().strip() for x in tds[0].find_all('tr') if len(x.get_text().strip()) > 0]
get_text() 和 strip() 方法是否计算了两次?有没有更好的写法?
谢谢
您可以使用 filter
删除空字符串。
vals = list(filter(None, [x.get_text().strip() for x in tds[0].find_all('tr')]))
在用 Python 编写一些网络爬虫代码时,我的需求是这样的:
vals = [x.get_text().strip() for x in tds[0].find_all('tr') if len(x.get_text().strip()) > 0]
get_text() 和 strip() 方法是否计算了两次?有没有更好的写法?
谢谢
您可以使用 filter
删除空字符串。
vals = list(filter(None, [x.get_text().strip() for x in tds[0].find_all('tr')]))