![]() |
BASIC to python3: using lists like arrays - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: BASIC to python3: using lists like arrays (/thread-1330.html) |
BASIC to python3: using lists like arrays - nigeljbm - Dec-24-2016 New to python - just installed python3/ktinter in ubuntu/lubuntu system. Been through a lot of tutorials etc but none of them explain in practical terms how to populate lists to resemble a two-dimensional array. (They usually show a few keyed lists then all the slicing etc stuff to manipulate these lists not how to use a loop to get the data INTO the lists). I have a suite of stats software written in QB64 that I'm going to reprogram over time into python3. In these I would do something like: dim myArray(10,20) for x=1 to 10 for y=1 to 20 let myArray(x,y)=(x-y) 'populate array with data using a formula next y next x for x=1 to 10 for y=1 to 20 print myArray(x,y) 'output contents - could also be print to file next y next x All my stuff will be 2-dimensional. (installed numpy but will probably avoid using) All the other functionality I need to use python to re-write my software looks covered and there is so much good, compact stuff I can use. But none of the tutorial material I've seen covers the simple populate/print/save arrays functionality above. An example of how to deal with this would be appreciated. RE: BASIC to python3: using lists like arrays - Yoriz - Dec-24-2016 my_array = [[0 for y in range(20)] for x in range(10)] #dim myArray(10,20) for x in range(10): #for x=1 to 10 for y in range(20): #for y=1 to 20 my_array[x][y] = (x+1)-(y+1) #let myArray(x,y)=(x-y) 'populate array with data using a formula # next y # next x for x in range(10): #for x=1 to 10 for y in range(20): #for y=1 to 20 print(my_array[x][y])# print myArray(x,y) 'output contents - could also be print to file # next y # next x The creation and setting of values of my_array can be done in the list comprehension my_array2 = [[(x+1)-(y+1) for y in range(20)] for x in range(10)] print(my_array == my_array2)
RE: BASIC to python3: using lists like arrays - nigeljbm - Dec-26-2016 Many thanks - you answered my query completely. The list comprehension example is really compact and neat - one line of code, easier to read and correct. |