[英]python itertools combinations including auto-correlations
Is there an elegant/pythonic way to retrieve both the cross- and auto-correlations of elements of a list? 有没有检索列表中元素的两个交叉和自相关优雅/ Python的方式?
I could do this manually, though I'd like to try and use itertools.combinations
, which by default doesn't seem to produce auto-correlations [(1,1), (2,2), etc.]. 我可以手动执行此操作,尽管我想尝试使用
itertools.combinations
,默认情况下它似乎不会产生自相关[[1,1),(2,2)等。
This question actually deals with the cross -correlations only: 这个问题实际上只处理交叉相关:
Calculating correlations between every item in a list 计算列表中每个项目之间的相关性
Try this for a MWE: 尝试使用MWE:
import itertools
data = range(4); crosscorrs=[]
# Get the cross-correlations:
for (i,j) in itertools.combinations(data, 2):
crosscorrs.append((i,j))
# How to get the auto-correlations?
# What about the (j,i) correlations even?!
# Result
print crosscorrs
What about the (j,i) correlations even!? 那(j,i)的相关性呢!
Thanks for all help 感谢所有帮助
There is a number of things wrong with the question, including a piece of example code which will raise an Exception
, but I will attempt to address what you seem to be asking. 这个问题有很多问题,包括一段引发
Exception
的示例代码,但是我将尝试解决您似乎在问的问题。
As you name the collection "crosscorrs" I take it you want separate lists for "crosscorrelation" indices and "autocorrelation" indices. 当您将集合命名为“ crosscorrs”时,我想您需要“ crosscorrelation”索引和“ autocorrelation”索引的单独列表。 To get the (j,i) indices, you can just refer to them as such.
要获得(j,i)索引,您可以这样引用它们。 The same-index-stuff can be added to a set, to avoid having duplicates.
可以将相同索引的东西添加到集合中,以避免重复。
from itertools import combinations
data = range(4)
crosscorrs=[]
autocorrs = set()
for (i,j) in combinations(data,2):
crosscorrs.extend([(i,j),(j,i)])
autocorrs.add((i,i))
autocorrs.add((j,j))
print(crosscorrs, '\n')
print(list(autocorrs))
If you would want all of this to go into 1 collection, take a look at itertools.combinations_with_replacement
and the option to reverse data
by data[::-1]
. 如果您希望所有这些
itertools.combinations_with_replacement
为1个集合,请查看itertools.combinations_with_replacement
以及按data[::-1]
反转data
的选项。 Quite possibly, a set
can come in handy, as it supports union
operations. 一
set
很可能派上用场,因为它支持union
操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.