El lunes, 9 de enero de 2017, 14:09:09 (UTC+1), José Manuel Suárez Sierra escribió: > Hello, I am trying to make a code wich compares between 2 or several > sequences (lists). It compares every element in a list with another list > elements. For example, if we have a list_a=["a","b","c","d"] and > list_b=["a","b"] I want to obtain a new list_c containing elements that match > between these lists (a and b here), but, if for instance list_b were > ["a","c"] the program must not store this data because they are not in same > order. > > Said this, I wrote this code but it doesnt work: > > if __name__ == "__main__": > > > def compare(a, b): > > i = 0 > j = 0 > c1 = [] > > while a[i] == b[j]: > c1.append(a[i]) > j = j+1 > i=i+1 > > return c1 > > > > > cadena_1=raw_input("Introduce list 1 \n") > cadena_2 = raw_input("Introduce list 2 \n") > > > transf1=list(cad_1) > transf2 = list(cad_2) > > > print compare(transf1,transf2) > > > > > Thank you
Thank you! Here is my code, I dont understand why it doesnt work very well: if __name__ == "__main__": cadena_1 = raw_input("Introduce la cadena 1 \n") cadena_2 = raw_input("Introduce la cadena 2 \n") # n=input("De cuantas letras quieres hacer la comparacion?\n") transf1 = list(cadena_1) transf2 = list(cadena_2) l1=len(transf1) l2=len(transf2) c3=[] i=0 j=0 for transf1[i] in transf1: for transf2[j] in transf2: if transf1[i]==transf2[j]: c3.append(transf1[i]) i=i+1 j=j+1 else: j=j+1 print c3 This is the traceback: line 18, in <module> for transf2[j] in transf2: IndexError: list assignment index out of range If I have initialized j=0 (such as i) why does it not work? I want the script to read sequence 1 and compares every element inside it with elements in sequence 2 no mattering where it matches. Thank you! -- https://mail.python.org/mailman/listinfo/python-list