[英]Is there a simple way to randomly pick from a list with the exception of one element?
[英]Simple way of excluding an element from a calculation on a list?
例如,我想检查两个列表之间的相关系数,例如:
r = np.corrcoef(list25, list26)[0,1]
但我想从计算中排除列表中的-1。 是否有一种简单的单线方法来执行此操作,而不是制作列表的新副本并进行迭代以删除所有-1等?
有一个内衬解决方案。 它正在创建一个没有列表的新列表。 可以使用List Comprehension来完成:
new_list = [x for x in old_list if x != -1]
它基本上将符合条件的所有内容从旧列表复制到新列表。
因此,以您的示例为例:
r = np.corrcoef([x for x in list25 if x != -1], [x for x in list26 if x != -1])[0,1]
使用发电机
def greater_neg_1(items):
for item in items:
if item>-1:
yield item
用法:
>>> L = [1,-1,2,3,4,-1,4]
>>> list(greater_neg_1(L))
[1, 2, 3, 4, 4]
要么:
r = np.corrcoef(greater_neg_1(list25), greater_neg_1(list26))[0,1]
不需要任何额外的内存。
如果您实际上要从列表中删除-1
:
while -1 in list25: list25.remove(-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.