简体   繁体   English

查找2d数组元素的第一元素和第二元素之间的最大和最小差异

[英]Finding biggest and smallest difference between 1st and 2nd element of 2d array elements

I made a function which takes a list of 2d elements(containing lists with 2 elements) as an argument and returns the element(or elements) whose elements' difference is the biggest and the one(or more) whose elements' difference is the smallest. 我制作了一个函数,该函数将一个2d元素的列表(包含包含2个元素的列表)作为参数,并返回其元素差最大的一个(或多个)元素和其元素差最小的一个(或多个)元素。 For example, given an argument ([2,8],[3,4],[2,7],[4,10]), the function would return: max=([2,8], [4,10]), min=[3,4]. 例如,给定参数([2,8],[3,4],[2,7],[4,10]),该函数将返回:max =([2,8],[4,10 ]),最小值= [3,4]。

I have made a function that does that, but the code is rather big, without me adding the part which I fill the list to be passed as argument with user input,which I also want to do. 我已经创建了一个可以执行此操作的函数,但是代码相当大,没有添加我填充列表的那一部分,该部分也将作为用户输入参数传递给用户,我也想这样做。

def maxminIntervals(lst):
 mx=lst[0][1]-lst[0][0]
 mn=mx
 count_max=count_min=0

 max=[]
 min=[]
 print(max,min)
 print(mx,mn)
 for element in lst:
    y=element[1]-element[0]
    if y>mx:
        max=[]
        max.append(element)
        count_max=0
        mx=y
    elif y==mx:
        max.append(element)
        mx=y
        count_max+=1
    if y<mn:
        min=[]
        min.append(element)
        count_min=0
        mn=y
    elif y==mn:
        min.append(element)
        mn=y
        count_min+=1
    print(y)
 print("Max=",end='')
 if count_max>0:
        print("(",end=" ")
 for i in max:
    print(i,end=' ')
 if count_max>0:
        print(")",end=" ")
 print("\n")
 print("Min=",end=' ')
 if count_min>0:
        print("(",end=" ")
 for i in min:
    print(i,end=' ')
 if count_min>0:
    print(")",end=" ")

It seems to me the code is too big for Python. 在我看来,代码对于Python来说太大了。 Is there a simple shortcut(built-in function, etc) to make it shorter? 是否有一个简单的快捷方式(内置函数等)使其更短?

if you want to keep the all the pairs, if it is the maximun/minimun, you can try this (I have commented where I simplify it): 如果要保留所有对,如果是最大/最小,则可以尝试执行此操作(我已在简化的地方进行了评论):

def maxminIntervals(lst):
    max_diff, min_diff = float('-inf'), float('inf')
    max_results, min_results = [], []
    # for loop and unzip pairs to num1, num2
    for num1, num2 in lst:
        # define diff to compare min and max
        diff = num2 - num1
        # append to max_results
        if diff == max_diff:
            max_results.append([num1, num2])
        # update a new max_results
        elif diff > max_diff:
            max_diff = diff
            max_results = [[num1, num2]]

        # append to min_results
        if diff == min_diff:
            min_results.append([num1, num2])
        # update a new min_results
        elif diff < min_diff:
            min_diff = diff
            min_results = [[num1, num2]]
    return max_results, min_results

def test():
    lst = ([2, 8], [3, 4], [2, 7], [4, 10])
    max_results, min_results = maxminIntervals(lst)
    print('max results:', max_results)
    print('min results:', min_results)

output: 输出:

max results: [[2, 8], [4, 10]]
min results: [[3, 4]]

Here is a 4-line solution, more pythonic, but cost more: 这是4行解决方案,使用pythonic,但价格更高:

from collections import defaultdict
from operator import itemgetter

def maxminIntervals2(lst):
    diff_dict = defaultdict(list)
    for pair in lst:
        diff_dict[pair[1] - pair[0]].append(pair)
    return max(diff_dict.items(), key=itemgetter(0))[1], min(diff_dict.items(), key=itemgetter(0))[1]

Hope that will help you, and comment if you have further questions. 希望对您有所帮助,如有其他问题,请发表评论。 : ) :)

The main idea is to keep track of the min and max values but also have separate lists to keep track of each pair 主要思想是跟踪minmax但还有单独的列表以跟踪每一对

def maxMinIntervals(lst):
    maximum, minimum = [], []
    max_value, min_value = float('-inf'), float('inf')
    for pair in lst:
        value = abs(pair[1] - pair[0])
        if value > max_value:
            max_value = value
            maximum = []
            maximum.append(pair)
        elif value == max_value:
            maximum.append(pair)
        if value < min_value:
            minimum = []
            minimum.append(pair)
            min_value = value
        elif value == min_value:
            minimum.append(pair)
    return maximum, minimum 

Driver 司机

input_list = [[2,8], [3,4], [2,7], [4,10]]
max_ans, min_ans = maxMinIntervals(input_list)
print('maximum results: ', max_ans)
print('minimum results: ', min_ans)

Output 产量

('maximum results: ', [[2, 8], [4, 10]]) (“最大结果:”,[[2、8],[4、10]])

('minimum results: ', [[3, 4]]) (“最小结果:”,[[3,4]])

暂无
暂无

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

相关问题 比较2D列表的第一个元素并在第二个元素上进行操作 - Compare 1st element of a 2D list and operate on 2nd element 如何在python中的2D列表中比较第一个元素并操作第二个元素 - How to compare 1st element and operate 2nd element in 2D list in python for循环跳过第一和第二元素 - for loop skipping 1st and 2nd element 如何在python numpy的二维数组中将位置(第2、第3或第4等)转换为索引(第1位置为00,第2位置为01等)? - how can I convert position (2nd, 3rd or 4th etc ) to index(00 for 1st position, 01 for 2nd etc) in 2D array in python numpy? 从2D数组中,不使用循环就从第1个数组(不在行之间共享的值)创建唯一(非重复)随机选择值的第2个2D数组 - From a 2D array, create 2nd 2D array of Unique(non-repeated) random selected values from 1st array (values not shared among rows) without using a loop 首先按第 1 列然后按第 2 列对 2D 列表进行排序 - sort a 2D list first by 1st column and then by 2nd column 如何对列表列表进行排序并按间隔仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements by intervals? 如何对列表列表进行排序并仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements? 无法获取列表的第一个和第二个元素 - Cannot get 1st and 2nd element of a list 在python中获取第一个和第二个管道之间的数据 - Get data between 1st and 2nd pipe in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM