the script can not go through all the list, anyone could help, would be highly appreciated, thanks a lot !

MRAB python at mrabarnett.plus.com
Tue Jan 31 20:06:15 EST 2012


On 01/02/2012 00:00, Para wrote:
> the script can not go through all the list, anyone could help, would be
> highly appreciated, thanks a lot !
>
> output:
> initial 7 lines:
> [9379, 'G', '0.1830']
> [9378, 'G', '0.1752']
> [9377, 'G', '0.1929']
> [9375, 'G', '0.1950']
> [9370, 'G', '0.1872']
> [937, 'G', '0.1931']
> [93, 'G', '0.1974']
> processing:
> code_K = 93 rate_K = -1 len_K = 1 len_G = 7
> code_K = 93 rate_K = 0.1830 code_G = 9379 rate_G = 0.1830
> code_K = 93 rate_K = 0.1929 code_G = 9377 rate_G = 0.1929
> code_K = 93 rate_K = 0.1929 code_G = 9370 rate_G = 0.1872
> code_K = 93 rate_K = 0.1974 code_G = 93 rate_G = 0.1974
> final 3 lines:
> [9378, 'G', '0.1752']
> [9375, 'G', '0.1950']
> [937, 'G', '0.1931']
>
>
> code:
> ...... # read data from .csv
> print "initial", len(list_G), "lines:"
> for row_G in list_G:
>     print row_G
>
> print "processing:"
> for row_K in list_K:
>     code_K = str(row_K[0])
>     rate_K = -1
>     len_K = len(list_K)
>     len_G = len(list_G)
>     print "code_K =", code_K, "rate_K =", rate_K, "len_K =", len_K, "len_G =", len_G
>     for row_G in list_G:
>         code_G = str(row_G[0])
>         rate_G = str(row_G[2])
>         if re.match(code_K, code_G):
>             if rate_K < rate_G:
>                 rate_K = rate_G
>             print "code_K =", code_K, "rate_K =", rate_K, "code_G =", code_G,
>             "rate_G =", rate_G
>             list_G.remove(row_G)
>
> print "final", len(list_G), "lines:"
> for row_G in list_G:
> print row_G

rate_K is initially a number (rate_K = -1), but rate_G is a string. If
you want to compare numeric values, make sure that they are both
numbers. (In Python 3 it will complain if you say x < y when one of
them is a string and the other is a number; in Python 2 it will return
a consistent but arbitrary result.)

The re.match(code_K, code_G) checks whether code_G start with code_K.
It is better to use code_G.startswith(code_K) instead.

Also, you have:

     for row_G in list_G:
         ...
         list_G.remove(row_G)

Don't add or remove items in a list over which you are iterating.



More information about the Python-list mailing list