Skip to main content
 首页 » 编程设计

Python如何从for循环中的字典列表中删除空行

2025年05月04日9qlqwjy

我有一个名为“行”的字典列表。但是,此列表包含一些具有空值(标记为“无”)的字典。如果在名为“lat”的键中找到“None”,我该如何编写遍历每一行并删除整行的 for 循环?

这是我的字典列表(“行”)。我想编写一个删除第一行的 for 循环,因为“lat”值为“None”。任何帮助将不胜感激!

[{'created_at': None, 'userid': None, 'long': None, 'tweetid': None, 'timestamp': None, 'lat': None}, 
 {'created_at': 'Mon May 04 04:35:34 +0000 2015', 'userid': '113503286', 'long': '-87.624387', 'tweetid': '595084326489956352', 'timestamp': '1430714134224', 'lat': '41.852653'},  
 {'created_at': 'Mon May 04 04:35:46 +0000 2015', 'userid': '2421024865', 'long': '-87.629798', 'tweetid': '595084376632729600', 'timestamp': '1430714146179', 'lat': '41.878114'}] 

请您参考如下方法:

List Comprehensions 是必经之路。

rows = [{'created_at': None, 'userid': None, 'long': None, 'tweetid': None, 'timestamp': None, 'lat': None}, 
 {'created_at': 'Mon May 04 04:35:34 +0000 2015', 'userid': '113503286', 'long': '-87.624387', 'tweetid': '595084326489956352', 'timestamp': '1430714134224', 'lat': '41.852653'},  
 {'created_at': 'Mon May 04 04:35:46 +0000 2015', 'userid': '2421024865', 'long': '-87.629798', 'tweetid': '595084376632729600', 'timestamp': '1430714146179', 'lat': '41.878114'}] 
rows = [ row for row in rows if row['lat'] is not None ] 

你可以阅读 list comprehensions documentation了解更多。