繁体   English   中英

在Python中比较3个列表的值的有效方法?

[英]Efficient way to compare the values of 3 lists in Python?

我在a1,a2,a3(长度相等)中有3个具有相似浮点值的列表。

for i in length(a1,a2,a3):
  Find the increasing / decreasing order of a1[i], a2[i], a3[i]
  Rank the values based on the order 

有没有简单/有效的方法来做到这一点? 而不是编写if-else语句块?

我正在尝试计算Python中的Friedman测试等级。 尽管有一个scipy.stats.friedmanchisquare函数,但它不会返回排名The Friedman test

编辑

我在图像1中有这样的数据。

  • A1有第1周
  • a2有第2周,
  • a3有第3周,我想对这张图片2中的值进行排名

我尝试通过使用if else循环来比较值

for i in range(0,10):
if(acc1[i]>acc2[i]):
    if(acc1[i]>acc3[i]):
        rank1[i] = 1
        if(acc2[i]>acc3[i]):
            rank2[i] = 2
            rank3[i] = 3

friedmanchisquare使用scipy.stats.rankdata 这是将rankdata与三个列表一起使用的一种方法。 它创建一个名为ranks的列表,其中ranks[i]是包含[a1[i], a2[i], a3[i]]的排名的数组。

In [41]: a1
Out[41]: [1.0, 2.4, 5.0, 6]

In [42]: a2
Out[42]: [9.0, 5.0, 4, 5.0]

In [43]: a3
Out[43]: [5.0, 6.0, 7.0, 2.0]

In [44]: from scipy.stats import rankdata

In [45]: ranks = [rankdata(row) for row in zip(a1, a2, a3)]

In [46]: ranks
Out[46]: 
[array([ 1.,  3.,  2.]),
 array([ 1.,  2.,  3.]),
 array([ 2.,  1.,  3.]),
 array([ 3.,  2.,  1.])]

如果转换到一个numpy的数组,然后你可以轻松地与任意的行或列的工作ranks

In [47]: ranks = np.array(ranks)

In [48]: ranks
Out[48]: 
array([[ 1.,  3.,  2.],
       [ 1.,  2.,  3.],
       [ 2.,  1.,  3.],
       [ 3.,  2.,  1.]])

In [49]: ranks.sum(axis=0)
Out[49]: array([ 7.,  8.,  9.])

您可以定义一个简单的函数来返回排序顺序:

def sort3(a,b,c):
    if (a >= b):
        if (b >= c):
            return (1, 2, 3)
        elif (a >= c):
            return (1, 3, 2)
        else:
            return (3, 1, 2)
    elif (b >= c):
        if (c >= a):
            return (2, 3, 1)
        else:
            return (2, 1, 3)
    else:
        return (3, 2, 1)

或考虑使用此https://stackoverflow.com/a/3382369/3224664

def argsort(seq):
    # http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
    return sorted(range(len(seq)), key=seq.__getitem__)
a = [1,3,5,7]
b = [2,2,2,6]
c = [3,1,4,8]
for i in range(len(a)):
    print(argsort([a[i],b[i],c[i]]))

暂无
暂无

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

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