如何将列表中的项目与列表中的项目进行比较?

时间:2020-07-02 13:53:31

标签: python-3.x numpy for-loop

我想将列表a中的项目与列表x中的项目进行比较。想法是根据条件逐项进行比较,然后根据条件是否满足执行一些操作。但是,我必须遍历所有项目的想法不起作用。有没有一种有效的方法可以做到这一点?

x = [10, 11, 12]
a = [[11, 10, 12], [12, 15, 20], [11, 14, 16]]

for i, j in a, b: # I am looking for an alternative way to do this
    counter = []
    if i <= j: # if the item in a is equal to or smaller than the corresponding
               # item in list x, then the list is rejected and the counter is
               # increased by 1
        counter =+ 1
    else:
        print(counter, np.mean(a[-1])) # print the number of rejected lists

我期望的结果是:

1a中的列表1中,第二项小于x中的第二项和第三项,而第三项等于18中的第二项和第三项。

StorageReference其他两个列表不满足条件,因此可以,最后两个项目的平均值为(20 + 16)/ 2 = 18

2 个答案:

答案 0 :(得分:2)

如果您愿意将数组转换为numpy数组,则可以利用逐元素比较,从而避免完全迭代:

x = np.array(x)
a = np.array(a)

# numpy arrays allow the use of element-wise comparison
logic = x <= a
print("logic selection matrix:")
print(logic)

# flag entries that don't fully meet the conditions as dictated by the logic matrix
flags = np.sum(logic,axis=1) != 3

# counter of false entries
c = np.sum(flags)
print (f"final value of counter is {c}")

mean = np.mean(a[flags == False][:,-1])
print (f"found mean of entries is {mean}")

输出:

logic selection matrix:
[[ True False  True]
 [ True  True  True]
 [ True  True  True]]
final value of counter is 1
found mean of entries is 18.0

尽管如果除了添加计数器之外还需要执行更复杂的操作,则将很难实现。您还可以在保留if-else结构的同时部分使用此属性:

x = [10, 11, 12]
a = [[11, 10, 12], [12, 15, 20], [11, 14, 16]]

x = np.array(x)
a = np.array(a)

lastitems = []
for lst in a:
    if np.all(x <= lst):
        lastitems.append(lst[-1])
    else:
        c = np.sum(x <= lst)
        print(f"found {c} entries smaller than x array in list")
        
print(f"list of last_items: {lastitems}")
mean = np.mean(lastitems)
print(f"mean of last items: {mean}")

输出:

found 2 entries smaller than x array in list
list of last_items: [20, 16]
mean of last items: 18.0

答案 1 :(得分:0)

我希望这是您要寻找的东西:

import numpy as np
x = [10, 11, 12]
a = [[11, 10, 12], [12, 15, 20], [11, 14, 16]]

valid = []
for index, i in enumerate(a):
    for j in range(0, len(x)):
        if i[j] <= x[j]:
            print((index +1), '. In list ', str(index +1),  ', Item ', str(j+1), ' is smaller than item ', str(j+1), ' in x')
            break
        else:
            if(j == len(x) - 1):
                print((index +1), '. List ', str(index +1),  ' is ok ')
                valid.append( i[-1])
print('================')
print('Average = ', np.mean(valid)) # print the number of lists