繁体   English   中英

比较多个列表中的数字 Python

[英]Comparing Numbers in Multiple Lists Python

我有 5 组如下所示的值:

[[83.91649562 79.51353257]
 [87.57474691 84.66544614]
 [84.08067077 85.19063777]
 [86.97440657 86.20994142]
 [82.91694642 84.65734125]]

我的目标是将每组中的两个值与此标准进行比较:

  1. 在任何列表中,如果 item1 和 item2 >= 80 AND item1 < item2,则返回 -10
  2. 在任何列表中,如果 item1 和 item2 <= 20 AND item1 > item2,则返回 10
  3. 否则返回 0

这是我所做的

def myfunction(data):
    data = data.iloc[:, [0, 1]].values
    for x, y in enumerate(data):
        if (x-y).all() >= 80 and x < y:
            return -10
        else:
            return 0

现在我返回 0,但是第 3 和第 5 个列表符合条件并且应该返回 -10,所以我没有转到第二个 if 语句。 我还尝试使用以下方法设置数据:

data = data.iloc[:, [0, 1]].values.tolist()

将数据用作

[[83.91649561983937, 79.51353257164777], [87.57474691499445, 84.66544613660386], [84.08067077024245, 85.19063776835876], [86.97440656949847, 86.20994141824511], [82.91694641784167, 84.65734125252753]]

没有运气。 我一直在使用 enumarate() 因为我在没有收到错误消息方面取得了最大的成功,但我不确定这是否是我解决这个问题所需要的。

谢谢大家!

不使用任何库,为简化起见,您可以像这样编写循环

#Devil
lst = [[83.91649562, 79.51353257],
    [87.57474691, 84.66544614],
    [84.08067077, 85.19063777],
    [86.97440657, 86.20994142],
    [82.91694642, 84.65734125]]

fill_out = []
for i in lst:
    #print(i)
    item1 = i[0] ; item2 = i[1]
    if item1 >= 80 and item2 >= 80 and item1 < item2:
        fill_out.append(-10)
    elif item1 <= 20 and item2 <= 20 and item1 > item2:
        fill_out.append(10)
    else:
        fill_out.append(0)

print("output:",fill_out)
#output : [0, 0, -10, 0, -10]

您可以尝试以下方法:

import numpy as np

a = np.array([[83.91649561983937, 79.51353257164777],
              [87.57474691499445, 84.66544613660386],
              [84.08067077024245, 85.19063776835876],
              [86.97440656949847, 86.20994141824511],
              [82.91694641784167, 84.65734125252753]])

conds = [(np.diff(a) > 0).ravel() & np.all(a >= 80, axis=1),
         (np.diff(a) < 0).ravel() & np.all(a <= 20, axis=1)]
np.select(conds, [-10, 10])

它给:

array([  0,   0, -10,   0, -10])
import pandas as pd


def myfunction(data):
    where = (data[0] >= 80) & (data[1] >= 80) & (data[0] < data[1])
    if len(data.loc[where]) > 0:
        return -10 

    where = (data[0] <= 20) & (data[1] <= 20) & (data[0] > data[1])
    if len(data.loc[where]) > 0:
        return 10

    return 0


data = pd.DataFrame([
    [83.91649562, 79.51353257],
    [87.57474691, 84.66544614],
    [84.08067077, 85.19063777],
    [86.97440657, 86.20994142],
    [82.91694642, 84.65734125],
])

myfunction(data)

基于初始代码(.iloc[]、.any())制作了这个函数,假设 OP 使用 pandas。

输出:-10

暂无
暂无

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

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