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

2024-04-24 13:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在用Python2.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]

我使用python2.7(Anaconda)、Spyder IDE和windows10。你知道吗

非常感谢您的帮助。你知道吗

谢谢你!你知道吗


Tags: 数据方法脚本示例列表参数绘制element
3条回答
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]

给你

[(x, y) for (x, y) in zip(list1, list2) if y != '']

另一个测试是测试类型is integer:isinstance(y, int),而不是y != ''。你知道吗

这应该是一个可行的解决方案:

list1 = [2000,2001,2002,2003,2004,2005,2006,2007]
list2 = [0,1,2,3,"",5,"",7]

reducedIndexes = [i for i,x in enumerate(list2) if x != '']

list1_reduced = [list1[i] for i in reducedIndexes] 
list2_reduced = [list2[i] for i in reducedIndexes]

缩减清单的内容:

[2000, 2001, 2002, 2003, 2005, 2007]
[0, 1, 2, 3, 5, 7]

相关问题 更多 >