Faster way of doing this:

#1

Hello

Before embarking on the "Battleship" course, I'm attempting to write the game solo, to better take in what I've learned so far, and while I'd like to figure everything out myself, there's one thing I just can't find a solution to:

The function that I've written:

``````def gridGenerator(string = "ABCDEFGHIJ"):
stringList = list(string)
emptyGrid = []
for i in stringList:
emptyGrid.append([i + str(1), i + str(2), i + str(3), i + str(4), i + str(5), i + str(6), i + str(7), i + str(8), i + str(9), i + str(10)])
return emptyGrid``````

Generates a list of lists for a grid of sorts that I intend to use for the this minigame

It outputs:

[['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10'], ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10'], ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10'], ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10'], ['E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9', 'E10'], ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10'], ['G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10'], ['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'H10'], ['I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9', 'I10'], ['J1', 'J2', 'J3', 'J4', 'J5', 'J6', 'J7', 'J8', 'J9', 'J10']]

My question is, is there a way to write a loop for this line

emptyGrid.append([i + str(1), i + str(2), i + str(3), i + str(4), i + str(5), i + str(6), i + str(7), i + str(8), i + str(9), i + str(10)])

Specifically so I wouldn't need to write str(1), str(2) and so on while defining the function?

#2

you could simply make a list with `"1","2"` and so on? then a simple loop should do the the trick

#3

Hi Stetim

Could you possibly show me what that loop would look like?
For some reason I'm having trouble figuring out how to create a loop which would essentially take two lists and output all the possible combinations of the strings of those two lists

#4

you simply create a nested loop:

``````for x in list1:
for y in list2:``````

this will cause the second loop to run fully every iteration/run of the first loop

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.