Python Forum
BASIC to python3: using lists like arrays
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BASIC to python3: using lists like arrays
#1
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.
Reply
#2
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)
Output:
True
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,378 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,915 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,286 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020