繁体   English   中英

在元组列表中的元组子集中查找第二个绝对值的最小值(python)

[英]Find minimum of absolute of second value in a subset of tuples in a list of tuples (python)

我有一个元组列表:

list = [(1,-1),(1,1),(2,0),(3,-9),(3,9),(4,-10),(4,-8),(4,8),(4,10),(5,-25),(5,25),(5,-9),(5,9)]

这是我想做的事情:

  • 对于第一个数字,即 1、2、3、4 和 5,找到 abs(第二个值)的最小值。 如果有多个最小值,找出所有最小值。 例如,对于“1”,(1,-1) 和 (1,1) 都符合条件,因为 abs(-1)=abs(1)
  • 创建另一个列表,在列表中的元组符合条件的相应位置为 1,在不符合条件的位置为 0。 答案是[1,1,1,1,1,0,1,1,0,0,0,1,1]

这是我的代码:

result=[]
temp_first=list[0][0]
temp_second=abs(list[0][1])
result.append(1)
for element in list[1:]:
    if element[0]==temp_first:
        if abs(element[1])<temp_second:
            result[-1]=0
            result.append(1)
        elif abs(element[1])>temp_second:
            result.append(0)
        else:
            result.append(1)          
    else:
        result.append(1)
        
    temp_first=element[0]
    temp_second=abs(element[1])        

它给了我[1,1,1,1,1,0,1,1,0,1,0,1,1]这是不正确的

任何帮助将不胜感激

尝试:

lst = [
    (1, -1),
    (1, 1),
    (2, 0),
    (3, -9),
    (3, 9),
    (4, -10),
    (4, -8),
    (4, 8),
    (4, 10),
    (5, -25),
    (5, 25),
    (5, -9),
    (5, 9),
]

tmp = {}
for a, b in lst:
    tmp.setdefault(a, []).append(abs(b))
tmp = {k: min(v) for k, v in tmp.items()}

out = [int(abs(b) == tmp[a]) for a, b in lst]
print(out)

印刷:

[1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1]

我认为这样的事情最有意义:

output = []

# Iterate through the indexes (1, 2, 3, 4, 5).
for index in {tpl[0] for tpl in lst}:

    # Filter index-specific tuples [(1, -1), (1, 1)]
    index_list = list(filter(lambda tpl: tpl[0] == index, lst))

    # Get tuple with the smallest item (1, -1)
    smallest_in_list = min(index_list, key=lambda tpl: abs(tpl[1]))

    # Absolute value of the second number.
    smallest_item_in_list = abs(smallest_in_list[1])

    # Creates output list for current iteration.
    iter_output = [1 if abs(tpl[1]) == smallest_item_in_list else 0 for tpl in index_list]

    output.extend(iter_output)

暂无
暂无

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

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