Question

how do I create tuple from two randomly generated lists with separate function ? zip function will create only tuple of those two arrays as whole but I need the numbers to be coupled like (1,2),(3,4). Thanks.

import random
def ars():
    arr1 = []
    arr2 = []
    for i in range(10):
        x = random.randrange(100)
        arr1.append(x)
    for j in range(10):
        y = random.randrange(100)
        arr2.append(y)
    return(arr1,arr2)

x = ars()
print x
y = zip(ars())
print y
Était-ce utile?

La solution

zip function accepts multiple iterables as its arguments, so you simply have to unpack the values from the returned tuple with * (splat operator):

y = zip(*ars())

With zip(([1], [2])) only one iterable is submitted (that tuple).

In zip(*([1], [2])) you unpack 2 lists from tuple, so zip receives 2 iterables.

Autres conseils

You can avoid having to zip by using map

def ars(arr_len, rand_max):
    return [map(random.randrange, [rand_max]*2) for x in range(arr_len)]

call ars like: ars(10,100), if you really need tuples instead of lists, wrap the map statement in a tuple() function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top