【问题标题】:Find minimum of absolute of second value in a subset of tuples in a list of tuples (python)在元组列表中的元组子集中查找第二个绝对值的最小值(python)
【发布时间】:2021-06-11 19:34:28
【问题描述】:

我有一个元组列表:

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] 这是不正确的

任何帮助将不胜感激

【问题讨论】:

    标签: python data-structures tuples


    【解决方案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]
    

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 2010-10-23
        • 2018-12-26
        • 2012-10-18
        • 2013-03-21
        • 2014-03-14
        • 1970-01-01
        相关资源
        最近更新 更多