简体   繁体   中英

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:

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:

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 .

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)

Then you could get the longest list by this method for example:

print(max(lists, key=len))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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