简体   繁体   中英

Using for loop with randint

Using this code:

from random import randint
ans = [[randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20)] for i in range(15)]
print (ans)

I got this:

[[10, 10, 13, 3, 13, 17, 3], [4, 1, 0, 15, 3, 9, 12], [8, 14, 8, 14, 2, 1, 11], [6, 13, 8, 9, 16, 18, 18], [10, 2, 15, 18, 16, 5, 4], [16, 3, 16, 9, 8, 20, 9], [1, 8, 16, 4, 7, 17, 20], [5, 0, 3, 11, 11, 3, 5], [17, 5, 14, 7, 20, 17, 17], [7, 4, 9, 17, 13, 0, 11], [3, 12, 6, 20, 9, 0, 3], [9, 12, 14, 16, 11, 4, 4], [12, 19, 12, 12, 11, 16, 12], [13, 15, 2, 3, 9, 17, 11], [14, 6, 10, 18, 8, 6, 6]]

But as you can see the repetition of randint(0,20) isn't good. Could you help me using something else, like a for loop, instead of repeating the same randint(0,20) ?

you could do a double list comprehension

from random import randint
ans = [[randint(0, 20) for j in range(7)] for i in range(15)]
print (ans)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM