Home > Net >  python3 - check element is actually in list
python3 - check element is actually in list

Time:11-24

for example i have excel header list like this

excel_headers = [
 'Name',
 'Age',
 'Sex',
]

and i have another list to check againt it.

headers = {'Name' : 1, 'Age': 2, 'Sex': 3, 'Whatever': 4}

i dont care if headers have whatever elements, i care only element in headers has excel_headers element.

WHAT I've TRIED

lst = all(headers[idx][0] == header for idx,
                    header in enumerate(excel_headers))
print(lst)

however it always return False.

any help? pleasse

CodePudding user response:

Another way to do it using sets would be to use set difference:

excel_headers = ['Name', 'Age', 'Sex']
headers = {'Name' : 1, 'Age': 2, 'Sex': 3, 'Whatever': 4}
diff = set(excel_headers) - set(headers)
hasAll = len(diff) == 0 # len 0 means every value in excel_headers is present in headers
print(diff) #this will give you unmatched elements

CodePudding user response:

Just sort your list, the results shows you a before and after

excel_headers = [
 'Name',
 'Age',
 'Sex',
]

headers = ['Age' , 'Name', 'Sex']

if excel_headers==headers: print "YES!"
else: print "NO!"

excel_headers.sort()
headers.sort()

if excel_headers==headers: print "YES!"
else: print "NO!"

Output:

No!
Yes!

CodePudding user response:

Tip: this is a good use case for a set, since you're looking up elements by value to see if they exist. However, for small lists (<100 elements) the difference in performance isn't really noticeable, and using a list is fine.

excel_headers = ['Name', 'Age', 'Sex']

headers = {'Name' : 1, 'Age': 2, 'Sex': 3, 'Whatever': 4}

result = all(element in headers for element in excel_headers)

print(result) # --> True
  • Related