Help with this code

José Manuel Suárez Sierra josemsuarezsierra at gmail.com
Mon Jan 9 08:46:44 EST 2017


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

Thanks for your reply,
I wrote this code:
 def comparar(cad1, cad2):
 i = 0
 j = 0
 cad3 = []
 k = True
 for cad1[i] in cad1:
 k = True
 for cad2[j] in cad2:
 while cad1[i] == cad2[j] and i<= len(cad1) and j <= len(cad2):
 cad3.append(cad1[i])
 i = i + 1
 j = j + 1
 if cad1[i] != cad2[j]:
 k = False
 i = i + 1
 return cad3
This is a function, another important thing is the order of elements, it must be ordered as it appears in one of the lists, in your example, my function must return a list with elements 1,2,5 in that order.
I cant find my mistake in these function I wrote you above.
Thank you very much


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /