简体   繁体   中英

Mutually exclusive arrays from an array of object based on some condition in python

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)

Lets assume that user gives m1 and m2 both as "happy" now both list will have same reviews. I want them to be exclusive list that means if a review is on list1 it shouldn't be on list2. I have solved this using a map object that will contain review id of reviews added to list1 and I will only add review to list2 if it's key-value pair is None.
But i feel there could be a better approach to this.

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.

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