Home > Software design >  How to create an array with arrays in one function
How to create an array with arrays in one function

Time:11-15

I am trying to create an output that will be an array that contains 5 "sub-arrays". Every array should include 10 random numbers between 0 and 10.

I have this code:

def count_tweets():
    big_array = []
    for i in range(5):
        array = []
        for p in range(10):
            array.append(random.randint(0,10))
        big_array.append(array)
        print(big_array)

I get a result like:

[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3], [2, 7, 1, 3, 8, 5, 7, 6, 0, 0]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3], [2, 7, 1, 3, 8, 5, 7, 6, 0, 0], [0, 1, 9, 9, 4, 2, 10, 4, 3, 8]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3], [2, 7, 1, 3, 8, 5, 7, 6, 0, 0], [0, 1, 9, 9, 4, 2, 10, 4, 3, 8], [3, 7, 3, 5, 4, 0, 2, 8, 6, 2]]

But instead it should be like:

[[0,2,6,7,9,4,6,1,10,5],[1,3,5,9,8,7,6,9,0,10],[3,5,1,7,9,4,7,2,7,9],[10,2,8,5,6,9,2,3,5,9],[4,5,2,9,8,7,5,1,3,5]]

I cannot seem to get the indentation correct. How do I fix the code?

CodePudding user response:

So what you did was put the print() statement inside a loop, which will print each time it runs.

    import random

    def count_tweets():
        big_array = []
        for i in range(5):
            array = []
            for p in range(10):
                array.append(random.randint(0,10))
            big_array.append(array)
        print(big_array)

    count_tweets()

Hope this helps :)

CodePudding user response:

You got it right, just slide the print out of the for loop.(delete four spaces before print())

  • Related