如何比较许多具有相同数量元素的列表

时间:2019-07-15 13:30:23

标签: python list max

我有一个测量系统。它每秒产生4个输出值。 4个值的列表(例如[30、45、70、10])。当我按下计算按钮时,它应该比较值。假设我3秒钟后按了计算按钮。因此,它将比较3个列表。比较意味着比较相同位置的元素。例如[10、5、23、24]和[22、35、45、12]是两个列表。第一个列表中的位置零元素(此处为10)应与第二个列表中的位置零元素(此处为22)进行比较,并在这两个列表中显示较高的值。与其他位置元素相同。这该怎么做。如何保存所有列表并进行比较?

# for demonstration, I am using  random number generator
import tkinter as tk
import random

measure_status = True

def readValues():
    if measure_status :
        outputs = [0]*0
        outputs.append(rand.randrange(0,100,1))
        outputs.append(rand.randrange(0,100,1))
        outputs.append(rand.randrange(0,100,1))
        outputs.append(rand.randrange(0,100,1))
       # do i need another variable to save all the list to compare
    win.after(1000, readValues)

def calc_max():

    global measure_status 
    measure_status = False  #stopping meaasurement.
# rest of the code here? how to compare lists?


win = Tk()

calc_btn  = tk.Button(win, text = "Calculate", command=calc_max )
calc_btn.grid(row=4, column=4)

win.after(1000, readValues)
win.mainloop()

1 个答案:

答案 0 :(得分:2)

您可以使用zipmax

def get_max_list(list_of_lists):
    """
    Returns a list of max values for the zips of list_of_lists.
    Assumes each list is the same length.
    """
    return [max(x) for x in zip(*list_of_lists)]

    # The above is equivalent to:
    # result = []
    # for x in zip(l1, l2, l3):
    #     result.append(max(x))
    # print(*result) # Just prints each entry in result.

l1 = [10, 5, 23, 24]
l2 = [22, 35, 45, 12]
l3 = [0, 22, 123, 33]
lists = [l1, l2, l3] # our list of lists example input
print(*get_max_list(lists))

输出:

22 35 123 33