문제

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
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top