Sort by Python column Question

Asked 2 years ago, Updated 2 years ago, 47 views


import operator

def sort_table(table, col):
  return sorted(table, key=operator.itemgetter(col))

x = [
      [4, 6, 3],
      [7, 5, 2],
      [1, 3, 8]
      ]

y = sort_table(x[0:3], 0)

for i in range(3):
        for j in range(3):
            print x[i][j],'\t',
        print('\n')

for i in range(3):
        for j in range(3):
            print y[i][j],'\t',
        print('\n')

x[0][0]=y[0][0]
x[1][0]=y[1][0]
x[2][0]=y[2][0]

print x

Result value is

[[1, 6, 3], [1, 5, 2], [1, 3, 8]]

It comes out as

[[1,6,3],[4,5,2],[7,3,8]]

Shouldn't it come out as?

python

2022-09-21 21:25

1 Answers

Typical show copy problem. Although x and y appear to be unrelated, in fact, x and y are reference relationships. So if you change x, y can be affected, and vice versa.

def sort_table(table, col):
  return sorted(table, key=operator.itemgetter(col))

x = [ [4, 6, 3], [7, 5, 2], [1, 3, 8] ]

y = sort_table(x[0:3], 0)

print "original:"
print y

print "after x[0][0]=y[0][0]:"
x[0][0]=y[0][0]
print y

Execution result:

original:
[[1, 3, 8], [4, 6, 3], [7, 5, 2]]
after x[0][0]=y[0][0]:
[[1, 3, 8], [1, 6, 3], [7, 5, 2]]

If you run this code, you'll get the hang of it. You only changed the value for x, but y[1][0] is also changed. If [[1,6,3],[4,5,2],[7,3,8]] appears when you run the uploaded code, replace the function sort_table as follows.

from copy import deepcopy

def sort_table(table, col):
  return deepcopy(sorted(table, key=operator.itemgetter(col)))

The deepcopy function used here breaks the rings of x and y to prevent further reference from occurring. How do I copy How do I copy the Python list? You can check it out at .


2022-09-21 21:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.