Hi,

i have a 2D list in python which i'm trying to fill using 2 for loops. but the problem is when i finish the filling procedure and i print the values, i find that they are not arrangeed in the order of input.

def funcdist(myarr):        
    diffs = 0
    testarr = []
    finarr = []
    for hx in range(len(myarr)):
        del testarr[:]
        for hy in range(len(myarr)):
            diffs=0
            for ch1, ch2 in zip(myarr[hx], myarr[hy]):
                if ch1 != ch2:
                    diffs += 1
            testarr.append(diffs)
        finarr.append((testarr))
    return finarr

in this case their should be some 0's in the diagonal, but when i print the array after i finish, i found that the 0's are all on the right side of the array. why this is happening?

and another question, how to add a column of 1 as the first column of the array?? i have no idea on how to do this.

Thank you

i managed to add a column of 1 using insert in numpy but still the problem of input order is not fixed ..

This should work

def funcdist(myvar):
    return [[ sum(1 for (a, b) in zip(line_a, line_b) if a != b)
            for line_b in myarr] for line_a in myarr ]

The problem in your snippet, is that a new testarr needs to be created in the hx loop. Replace line 6 by line 3 and discard line 3.

it works now, thank you. but can you please explain to me what's the difference ??

The difference is that in your first version, the same list object testarr is appended to finarr at line 13. In the end, all the lines in finarr are a single list object containing the values appended at the last iteration.

ok, now i get it.. thank you. problem solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.