As the title explains I want to create two mutually exclusive list (list1 and list2) from an array of objects matching some condition below is an example of objects
reviews = [
...
{
...
"mood": "happy"
...
},
{
...
"mood": "sad"
...
},
{
...
"mood": "neutral"
...
},
...
]
Now I am getting two moods from user as m1 and m2, I am looping over reviews array and adding each object to list1 if m1 == mood and to list2 if m2 == mood repectively.
list1 and list2 should have at most 5 reviews and they shouldn't be empty. It is guaranteed that m1 and m2 will always match reviews.
for review in reviews:
if review['mood'] == m1:
list1.append(review)
if review['mood'] == m2:
list2.append(review)
The most straightforward way would be to use elif
:
for review in reviews:
if review['mood'] == m1:
list1.append(review)
elif review['mood'] == m2:
list2.append(review)
In case the first if
condition is true, the second condition will not even be checked.
So, I think you need maintain a counter and that would solve your problem.
#m1==m2
count=0
for review in reviews:
if count%2==0:
list1.append(review)
else:
list2.append(review)
count+=1
Let me know this works for you!
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.