我是靠谱客的博主 不安路人,最近开发中收集的这篇文章主要介绍python将数放入列表,Python:将随机数放入列表,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Create a 'list' called my_randoms of 10 random numbers between 0 and 100.

This is what I have so far:

import random

my_randoms=[]

for i in range (10):

my_randoms.append(random.randrange(1, 101, 1))

print (my_randoms)

Unfortunately Python's output is this:

[34]

[34, 30]

[34, 30, 75]

[34, 30, 75, 27]

[34, 30, 75, 27, 8]

[34, 30, 75, 27, 8, 58]

[34, 30, 75, 27, 8, 58, 10]

[34, 30, 75, 27, 8, 58, 10, 1]

[34, 30, 75, 27, 8, 58, 10, 1, 59]

[34, 30, 75, 27, 8, 58, 10, 1, 59, 25]

It generates the 10 numbers like I ask it to, but it generates it one at a time. What am I doing wrong?

解决方案

You could use random.sample to generate the list with one call:

import random

my_randoms = random.sample(xrange(100), 10)

That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):

my_randoms = random.sample(xrange(1, 101), 10)

最后

以上就是不安路人为你收集整理的python将数放入列表,Python:将随机数放入列表的全部内容,希望文章能够帮你解决python将数放入列表,Python:将随机数放入列表所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部