python - 从两个列表中创建一个新列表,其中一个列表缺少数据 - 只应接受有效的对应值

标签 python database python-2.7 list

你好,我正在用 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/

相关文章:

python - IDLE 中带有 numpy 的 AttributeError 但 Python Shell 中没有

mysql - 如何执行从不同表返回唯一值的 mySQL 查询

php - 让 WordPress 读取自定义数据库

c# - 在 ListView 中显示数据库中的多列

python 添加两个列表并创建一个新列表

python - 使用 pycomm 将数据从 PLC 打印到 Python

Python I/O 读取和追加(写入)

python字典到重复列表

python - fit_generator() 以最小的验证损失保存模型

python - 将 optparse 转换为 argparse