Home > Mobile >  i want to loop through my nested list, search if a word is in it or not, and create an alias
i want to loop through my nested list, search if a word is in it or not, and create an alias

Time:10-13

I want it to search the entire list1 and sublists to make sure that the first_word is indeed in one of them, and then I want it to make sure that second_word is not already assigned to one of the lists in list_1. lastly i want it to append the second_word to to the list in list_1 that contains the first_word

list_1= [['test1', 'test2'],["test3"],["test4", "test5"],["test6"],["test7"]]   
list_2= ['123','234', '345','435','654']                                             


first_word= test1                                     
second_word = test6

for i in list_1:
    if second_word in i:
        print(second_word , "already assigned")
        break

    elif first_word not in i:
        print(first_word, "is not in list")
        break
    else:
        index = list_1.index((i))
        list_1[index].append(second_word)
        print(list_1)
        break

all these statements work on by themselves, but I can't seem to get them to work together.

by this I mean, it wont append if first_word is not present in list_1 or if the second_word is already in a list.

CodePudding user response:

This will iterate each item of list_1

  • check if first_word in each item
  • if first_word is in the item
    • check if second_word is in any of the list_1 items
    • if second_word is not in any of the list_1 items
      • append second_word to the item first_word was found in
list_1= [['test1', 'test2'],["test3"],["test4", "test5"],["test6"],["test7"]]   
list_2= ['123','234', '345','435','654']                                             

first_word = 'test1'                                     
second_word = 'test11'

for i in list_1:
    if first_word in i and not any([second_word in i for i in list_1]):
        i.append(second_word)
print(list_1)

returns:

[['test1', 'test2', 'test11'], ['test3'], ['test4', 'test5'], ['test6'], ['test7']]
  • Related