Compare two lists and search for change indices

I am trying to compare two lists and find a position and change the character in that position. For example, these are two lists:

list1 = ['I', 'C', 'A', 'N', 'R', 'U', 'N'] list2 = ['I', 'K', 'A', 'N', 'R', 'U', 'T'] 

I want to be able to display the position and change the differences in the two lists. As you can see, the letter can be repeated several times in a different index position. This is the code I tried, but I can not accurately print the second location.

 for indexing in range(0, len(list1)): if list1[indexing] != list2[indexing]: dontuseindex = indexing poschange = indexing + 1 changecharacter = list2[indexing] for indexingagain in range(dontuseindex + 1, len(list1)): if list1[indexingagain] != list2[indexingagain]: secondposchange = indexingagain + 1 secondchangecharacter = list2[indexingagain] 

Is there a better way to solve this problem or any suggestions for the code I have?

My expected result:

 2 K 7 T 
+5
source share
2 answers
 for index, (first, second) in enumerate(zip(list1, list2)): if first != second: print(index, second) 

Output:

 1 K 6 T 

If you want to get the result that you gave, we need to count from 1 instead of the usual 0 :

 for index, (first, second) in enumerate(zip(list1, list2), start=1): 
+7
source

Another option to save all unequal elements with an index with a list:

 list1 = ['I', 'C', 'A', 'N', 'R', 'U', 'N'] list2 = ['I', 'K', 'A', 'N', 'R', 'U', 'T'] # Append index, element1 and element2 as tuple to the list if they are not equal changes = [(i, list1[i], list2[i]) for i in range(len(list1)) if list1[i] != list2[i]] print(changes) #prints [(1, 'C', 'K'), (6, 'N', 'T')] 

Not quite what you indicated as output, but it closes.

You can print the specified result using a loop:

 for i in changes: print(i[0] + 1, i[1]) # 2 K # 7 T 

The comments suggested several alternative ways to develop an understanding of the list:

  • Using enumerate and zip :

     changes = [(i, e1, e2) for i, (e1, e2) in enumerate(zip(list1, list2)) if e1 != e2] 
  • Using enumerate with start index and zip :

     changes = [(i, e1, e2) for i, (e1, e2) in enumerate(zip(list1, list2), 1) if e1 != e2] 
  • Using zip and itertools.count :

     import itertools changes = [(i, e1, e2) for i, e1, e2 in zip(itertools.count(), list1, list2)) if e1 != e2] 
  • Using zip and itertools.count with a starting index:

     changes = [(i, e1, e2) for i, e1, e2 in zip(itertools.count(1), list1, list2)) if e1 != e2] 

All of them produce the same result as the original, but use different (best) python functions.

+4
source

Source: https://habr.com/ru/post/1245123/


All Articles