简体   繁体   中英

Python comparing two list elements in Python 3

I have a creative problem that I want to solve.

Let's say if I have two list as below. I want to compare if all elements in the req_param list are also in the full_list. I know it is easy to do the same using a for loop and getting the answer. But I am trying to figure out if there is a python3 in-built fxn to do the same..

req_param = ['ele1','ele2','ele3','ele4]
full_param = [['ele1','ele2','ele3','ele4','ele6'] 

During the comparison, I don't care if there are additional elements in full_param list. I just care that if full_param has all the elements of the req_param, then somehow I want to return it true else, I want to return it false.

Currently, this works with the for loop. But really think there should be an inbuilt fxn like compare. The most important part is that each element may not come in the same order, so I am ok to sort my list before passing it to a fxn...

As was mentioned there are several ways:

  1. Use all(): if all(item in full_list for item in req_param):
  2. Use set(): if set(req_param).issubset(set(full_param)):

I figured out a different way you can solve the problem.

You could just use set() and len() to solve the problem instead of for loop

Here's how:

r = ['ele1','ele2','ele3','ele4']
f = ['ele1','ele2','ele3','ele4','ele6']
print(len(set(r)-set(f))==0)

use all keyword, it returns True if all the conditions are satisfied else it returns False

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