I have a list like this.
l=[[['item1','item2'],[int1,int2]], [['item3','item4'],[int1,int2]]]
I want to check If item1 & item2 both are same or not..
Currently, I'm following a approach extracting first element in sub list & Thereby counting occurrence..But I feel like It's long approach. Can I know if there is any easy way to do it?
f=[e[0] for e in l[:1]]
print(f)
output
['item1']
Expected output. if item1 & Item2 are same.
Both item1 & Item2 are same
if item1 & Item2 are not same.
Both item1 & Item2 are not same
A very simple check for whether all the elements in a list are the same is
len(set(l)) == 1
So if you need to check if each element of a list contains idenitcal elements:
result = [len(set(s)) == 1 for s in l[0]]
This returns a list of booleans, which you can then transform into strings or whatever you want. For example:
for b in result:
print(f'Both item1 & item2 are {"" if b else "not "} the same')
In case that you want to compare all the 'item's in the list, you can loop the list and compare first item with second item like this:
l = [
[['item2','item2'], [int,int]],
[['item3','item4'], [int,int]]
]
for item in l:
if item[0][0] == item[0][1]:
print(f"Both {item[0][0]} & {item[0][1]} are same")
else:
print(f"Both {item[0][0]} & {item[0][1]} are not same")
#This code will print:
#Both item2 & item2 are same
#Both item3 & item4 are not same
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.