0

I have 3 below lists. I want to create an expected_list that has the same shape with list 1 and will contain element in list 2 if the element in list1 has "Review at", otherwise it will be blank ("")

list1 = [  "Review abcd"
           "Neu"
           "Review defg"
           "Review hmk"
           "hmd"
           "Review lmi"
           "Review yuj"
           "jmf"
           "Review  Bad"]

list2 = [ "http1"
          "http2"
          "http3"
          "http4"
          "http5"
          "http6"]

expected_list = [ "http1"
                  ""
                  "http2"
                  "http3"
                  ""
                  "http4"
                  "http5"
                  ""
                  "http6"]    

I tried the following code

for idx, item in enumerate(list1): 
    if "Review" in list1[idx]:
        for j in rang(len(list2))
            expected_list.append(list2[j])
    else:
        expected_list.append("")

However, in each element that satisfies the condition, it appends all the element in list2. So the shape of the expected list is more than expected. I know creating the 2nd loop is wrong. But how can i fix it ?

2
  • 1
    need comma seperated values Commented Dec 14, 2020 at 23:07
  • What have you tried to debug why your code is not working? Commented Dec 15, 2020 at 7:03

2 Answers 2

1

You simply need something like:

for idx, item in enumerate(list1): 
    if "Review" in item: # use *item* here, that's the whole point of enumerate
        expected_list.append(list2[idx])
    else:
        expected_list.append("")

Better yet, use zip:

for item1, item2 in zip(list1, list2):
    if "Review" in item1:
        expected_list.append(item2)
    else:
        expected_list.append("")
Sign up to request clarification or add additional context in comments.

Comments

1

those lists are one element, you need to seperate values with commas:

need commas

also, you dont need a lot of stuff there:

j = 0
for each in list1: 
    if "Review" in each:
        expected_list.append(list2[j])
    else:
        expected_list.append("")
    j+=1

1 Comment

thank your. In my case, i should put j+=1 in under the line expected_list.append(list2[j]), because if there is no Review in each review, i dont want the index of list2 to increase. Btw thanks for shedding a light for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.