我正在从网页中抓取数据,当我将数据加载到列表的列表中时,它看起来像这样
[['text', 'text', '', '', 'text', 'text']]
我正在尝试从所有列表中删除空字符串,但到目前为止我尝试过的所有方法都不起作用。
results = []
for list in scrape_list:
for item in scrape_list:
if item != '':
results.append(item)
OUTPUT: [['text', 'text', '', '', 'text', 'text']]
scrape_list1 = list(filter(None, scrape_list))
OUTPUT: [['text', 'text', '', '', 'text', 'text']]``
我想知道这些索引是否实际上不是空字符串并且正在保存一个值。如果其他人遇到过这种情况,请随时告诉我发生了什么,因为我无法弄清楚。
最佳答案
我猜只是一个错字(正如 @chunjef 的评论中提到的):
results = []
for lst in scrape_list:
for item in lst: # do NOT iterate through scrape_list here!!
if item != '':
results.append(item)
scrape_list
中的单个项目是一个 list
并且肯定是 != ''
,所以这个内部列表附加到 results
,因此你的输出。 scrape_list
的嵌套性质也会使您的过滤语句失败。你可以使用
scrape_list1 = [s for l in scrape_list for s in filter(None, l)]
得到一个简单的字符串列表。
关于python - 抓取返回不为空的空列表索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43954891/