Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Comprehension of Sublists?

Using Python 3.0, how would I go about creating a list of 100 indices such like this:

grid_Sys = [['A0'],['A1'],['A2']....['A9'],['B0'],...[J9]]

I understand how to increase the order of letters by using the ord() and chr() functions. However, I do not understand how to go 10 index's over before switching for chr(ord('A')+1) = B.

Essentially, I want to get to a point where I can do something like this:

grid_Sys = [['A0','brown']...

But, that's just a simple append option with a random color.

like image 541
ThomasTaylor Avatar asked Dec 18 '22 08:12

ThomasTaylor


1 Answers

You do not need to make it that complicated. Simply use:

[['%s%s'%(i,j)] for i in 'ABCDEFGHIJ' for j in range(10)]

No ord(..), chr(..) or complicated formulas: simpy a readable statement that shows what you aim to construct: usually if you have to do unreadable things, you are doing it wrong.

This gives:

>>> [['%s%s'%(i,j)] for i in 'ABCDEFGHIJ' for j in range(10)]
[['A0'], ['A1'], ['A2'], ['A3'], ['A4'], ['A5'], ['A6'], ['A7'], ['A8'], ['A9'], ['B0'], ['B1'], ['B2'], ['B3'], ['B4'], ['B5'], ['B6'], ['B7'], ['B8'], ['B9'], ['C0'], ['C1'], ['C2'], ['C3'], ['C4'], ['C5'], ['C6'], ['C7'], ['C8'], ['C9'], ['D0'], ['D1'], ['D2'], ['D3'], ['D4'], ['D5'], ['D6'], ['D7'], ['D8'], ['D9'], ['E0'], ['E1'], ['E2'], ['E3'], ['E4'], ['E5'], ['E6'], ['E7'], ['E8'], ['E9'], ['F0'], ['F1'], ['F2'], ['F3'], ['F4'], ['F5'], ['F6'], ['F7'], ['F8'], ['F9'], ['G0'], ['G1'], ['G2'], ['G3'], ['G4'], ['G5'], ['G6'], ['G7'], ['G8'], ['G9'], ['H0'], ['H1'], ['H2'], ['H3'], ['H4'], ['H5'], ['H6'], ['H7'], ['H8'], ['H9'], ['I0'], ['I1'], ['I2'], ['I3'], ['I4'], ['I5'], ['I6'], ['I7'], ['I8'], ['I9'], ['J0'], ['J1'], ['J2'], ['J3'], ['J4'], ['J5'], ['J6'], ['J7'], ['J8'], ['J9']]

Nevertheless I do not see why you want to construct list of lists? Usually if you want to "attach" properties on coordinates or other values, one uses a dictionary.

like image 57
Willem Van Onsem Avatar answered Dec 21 '22 09:12

Willem Van Onsem