你好,我正在用 Python 2.7 编写一个脚本来连接两个单独的列表,并创建一个没有缺失值但具有相应索引的新列表(请参见示例以获得更好的解释)。 假设我从源数据集中提取了两个列表:
- 列表 1 - 带有参数(例如年份)
- 列表 2 - 带有参数值
但是,并非所有参数都具有列表 2 中的值(缺失数据)。任务是创建两个列表,允许仅根据完整数据(对)绘制图表。
目前我正在使用下面的脚本,它运行良好。
我的问题:有没有更简单的方法来做到这一点?
特别是当有几个列表缺少数据时,这种方法会变得越来越难以管理。或者当提取的列表将包含 NaN 而不是空字符串“”时。
图书馆,有什么想法吗?
list1 = [2000,2001,2002,2003,2004,2005,2006,2007]
list2 = [0,1,2,3,"",5,"",7]
list1_reduced = []
list2_reduced = []
i=0
for element in list2:
if element != "":
list1_reduced.append(list1[i])
list2_reduced.append(list2[i])
i += 1
print list1_reduced
print list2_reduced
结果:
[2000, 2001, 2002, 2003, 2005, 2007]
[0, 1, 2, 3, 5, 7]
我使用 Python 2.7 (Anaconda)、Spyder IDE、Windows 10。
非常感谢任何帮助。
谢谢!
最佳答案
list1 = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007]
list2 = [0, 1, 2, 3, "", 5, "", 7]
list1, list2 = [list(z) for z in
zip(*[(x, y) for (x, y) in
zip(list1, list2) if y != ''])]
print(list1)
print(list2)
结果:
[2000, 2001, 2002, 2003, 2005, 2007]
[0, 1, 2, 3, 5, 7]
关于python - 从两个列表中创建一个新列表,其中一个列表缺少数据 - 只应接受有效的对应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44746198/