【问题标题】:How to compare the items in a lists of lists with the items in a list?如何将列表列表中的项目与列表中的项目进行比较?
【发布时间】:2020-07-02 13:53:31
【问题描述】:

我想将列表列表 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中,第2项小于x中的第2项和第3项。

18另外两个列表不满足条件所以没问题,它们最后一项的平均值是(20 + 16)/ 2 = 18

【问题讨论】:

  • 请让我知道为什么这个问题被否决了,这样我下次可以发布更好的问题。

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


【解决方案1】:

如果您愿意将数组转换为 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

【讨论】:

  • 非常感谢,这是一个不错的解决方案。第二种解决方案对我来说最有用。我只认为'if'子句中的条件在我的情况下应该是if np.all(x &lt; lst):,而不是&lt;=。在其他情况下,我需要一个柜台。但这很容易添加。
【解决方案2】:

我希望这是您正在寻找的:

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

【讨论】:

  • 非常感谢,非常好的解决方案。有用。打印语句准确显示违反条件的位置。我只需要一个计数器来计算已批准或未批准的列表。但这很容易解决。
  • 谢谢。如果它解决了您的问题,您可以将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多