繁体   English   中英

同时从两个列表中弹出值

[英]Popping values from two lists at same time

这里发生了一些奇怪的事情(至少对我来说很奇怪)。 我正在尝试从一个列表中弹出“ nan”值,并从另一列表中弹出相应的值。 得知您无法从正在枚举的列表中弹出,因此我做了一个临时列表。

import numpy as np
a=[]
b=[]

for i in range(0,100): #alternating list of ints and nan
    if i/2. == i/2:
        a.append(i)
    else: 
        a.append(np.mean([])) #the only way I know how to make nan
    b.append(i*100)

atemp=a
print(len(a),len(atemp))
for i,v in enumerate(atemp):
    if np.isnan(v):
        a.pop(i)
        b.pop(i)
print(len(a),len(atemp))

我不了解的情况正在发生:

1)它似乎是从atemp和a弹出nans,即使我只是告诉它a.pop(i)而不是atemp.pop(i)。 是否存在某种我未看到的函数重载或等于a和atemp的东西? 如何使它们完全独立(例如,仅从a弹出而不是atemp)?

2)它不会弹出所有nan,并且必须重复多次for循环才能弹出所有nan。

有很多简单的方法,但是如果您想使用自己的代码,则不仅需要复制 a创建引用并使用不同的逻辑从列表中删除元素,还可以将len -1反向循环遍历。您想要的输出:

import numpy as np

a = []
b = []

for i in range(0, 100):  # alternating list of ints and nan
    if i % 2 == 0:
        a.append(i)
    else:
        a.append(np.nan)  #the only way I know how to make nan
    b.append(i * 100)

atemp = a[:]
print(len(a), len(atemp))

for i in range(len(a)-1,-1,-1):
    if np.isnan(a[i]):
        a.pop(i)
        b.pop(i)
print(len(a), len(atemp))

那这个呢

# use this to filter None values in b
a, b = zip(*((x,y) for x,y in zip(a, b) if y))

# use this to filter np.nan in b
a, b = zip(*((x,y) for x,y in zip(a, b) if not np.isnan(y)))

做到了:

a, b = zip(*[(x,y) for x,y in zip(a, b) if np.isfinite(y)])

感谢大家。 抱歉,反叛的答案被否决了,因为它对我有很大帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM