简体   繁体   English

比较python中四个列表的更简单方法

[英]an easier way of comparing four lists in python

I have made four lists that all have some values and I want to say to computer to print the name of that list which has the greatest length. 我已经制作了四个都有一些值的列表,我想对计算机说,要打印长度最大的列表的名称。

I tried this code 我尝试了这段代码

list1=[values,values,values]
list2=[values,values,values]
list3=[values,values,values]
list4=[values,values,values]
if len(list1)>len(list2) and len(list1)>len(list3) and len(list1)>len(list4):
    print(True)

but it takes all my time and I need to compare list2 to others and list 3 and list4 so is there a way that I just do like this: 但是这需要我所有的时间,我需要将list2与其他对象以及list 3和list4进行比较,所以有一种方法可以像我这样:

if len(list1)>(len(list2) and len(list3) and len(list4)):
    print(True)

or this print(that list which has the greatest length) 或此打印(长度最大的列表)

What about using max: 如何使用max:

lists = (list1, list2, list3, list4)
print(max(lists, key=len))

Not sure if it's the optimal solution but you can make a function like such: 不知道这是否是最佳解决方案,但是您可以创建如下函数:

def check(main,*lists):
    for l in lists:
        if len(l) > len(main):
            return False
    return True

The biggest problem here is that it's really complicated to print variable names in python (Some explanations for example in the answers to this question . 这里最大的问题是,在python中打印变量名确实很复杂(例如,在此问题的答案中有一些解释。

The easiest way would be to rewrite the first assignments to use a dictionary: 最简单的方法是重写第一个作业以使用字典:

lists = {
  "list1": [ values ... ],
  "list2": [ values ... ],
  "list3": [ values ... ],
  "list4": [ values ... ]
}

(after that, instead of referring to list1, you have to refer to lists["list1"] instead) (此后,您不必引用list1,而必须引用lists["list1"]

Then you could get the longest list by this method for example: 然后,您可以通过这种方法获得最长的列表,例如:

print(max(lists, key=len))

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

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