In a file there is a list:

[['', '', '', '', '', '', '', '', '', 'Name'], ['', '', '', '', '', '', '', '', '', 1]]

How can I use it in a python script?

Thanks

Ah, thank you very much. Google failed me with that question. And sorry I'm new to python.

Anyone also know an easy way to sort the list so both lists stay relative but are ordered according to the second list.

Eg.

[1,2,3]

Should be:

[3,2,1]

As you can see, it is backwards. I made a solution for this but it obviously can't be the best way:

def sort_scores():
	#Sort scores according to number
	global score_data
	scores = sorted(score_data[1],reverse=True)
	names = [1] * len(score_data[1])
	for x in range(len(score_data[1])):
		i = scores.index(score_data[1][x])
		scores[i] = 0
		names[i] = score_data[0][x]
	score_data[0] = names
	score_data[1] = sorted(score_data[1],reverse=True)

I surely can't use that. I am surprised I got it to work.

A little experiment on the python console

>>> L = [list("cba"), list("123")]
>>> print L
[['c', 'b', 'a'], ['1', '2', '3']]
>>> print zip(*L)
[('c', '1'), ('b', '2'), ('a', '3')]
>>> S = sorted(zip(*L))
>>> print S
[('a', '3'), ('b', '2'), ('c', '1')]
>>> print [[x[0] for x in S],[x[1] for x in S]]
[['a', 'b', 'c'], ['3', '2', '1']]
Comments
nice code

To keep related things together, you might want to check into a dictionary:

# here a,3  b,2  and   c,1 are related pairs
q = [['c', 'b', 'a'], ['1', '2', '3']]
d = dict(zip(*q))
print d  # {'a': '3', 'c': '1', 'b': '2'}

for key in sorted(d):
    print key, '-->', d[key]

"""
my output -->
a --> 3
b --> 2
c --> 1
"""

There is a solution in one line of code, like this

>>> L = [('c', 'b', 'a'),('1', '2', '3')]
>>> print [ list(t) for t in zip(*sorted(zip(*L))) ]
[['a', 'b', 'c'], ['3', '2', '1']]

The trick is that zip(*L) is it's own inverse. It acts as matrix transpostion, consider the following example

>>> def vprint(L):
...  "prints a list vertically"
...  print "[\n  %s\n]" % "\n  ".join(repr(x)+"," for x in L)
...
>>> A = [ tuple(x**i for i in range(4)) for x in range(2, 5) ]
>>> vprint(A)
[
  (1, 2, 4, 8),
  (1, 3, 9, 27),
  (1, 4, 16, 64),
]
>>> B = zip(*A) # the transposed matrix
>>> vprint(B)
[
  (1, 1, 1),
  (2, 3, 4),
  (4, 9, 16),
  (8, 27, 64),
]
>>> C = zip(*B) # transpose once again
>>> vprint(C)
[
  (1, 2, 4, 8),
  (1, 3, 9, 27),
  (1, 4, 16, 64),
]
>>> C == A
True

So, in fact we defined sorting by columns, which we could formalize like this

>>> def column_sorted(M):
...  return zip(*sorted(zip(*M)))
...
>>> A = [
... (4, 8, 2, 1),
... (9, 27, 3, 1),
... (16, 64, 4, 1),
... ]
>>> vprint(column_sorted(A))
[
  (1, 2, 4, 8),
  (1, 3, 9, 27),
  (1, 4, 16, 64),
]

:)

This article has been dead for over six months. Start a new discussion instead.