Help with this code

Deborah Swanson python at deborahswanson.net
Mon Jan 9 08:39:33 EST 2017


José Manuel Suárez Sierra wrote, on January 09, 2017 5:09 AM
> 
> 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

I think your code assumes that a and b are the same length, and that all
the elements in the intersection (the ones in both lists) are in order
at the beginning of the list, like:

a = [1, 2, 5, 8, 22, 11, 14]
b = [1, 2, 5, 19, 12, 31, 42]

You only want to append the current list element if you test that it's
in both lists, and the answer is True. We do that with an 'if'
statement.

You need something like this, and a for loop would be the better choice
here.

cl = []
# look at every list element in 'a'
for c in a:
	# is this element in 'b'?
	if e in b:
		# if True, then append e to the result list, or continue
if False
		cl.append(e)
return cl

There's fancier ways to do it all in one line of code, but you need to
understand the fundamentals before you move on to tricks.

Deborah
		




More information about the Python-list mailing list