Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – สุ่มช่วงค่าในลิสต์ (Random Range)


เมื่อต้องการหาช่วงค่าสุ่มในลิสต์ ใช้ list comprehension และเมธอด 'randrange' ในแพ็กเกจ 'random'

ตัวอย่าง

สาธิตด้านล่าง:

import random 
my_result = [random.randrange(1, 100, 1) for i in range(10)] 
print ("The result is :") 
print(my_result)

ผลลัพธ์

The result is : [40, 73, 58, 45, 68, 19, 86, 6, 15, 71]

คำอธิบาย

  • นำเข้าแพ็กเกจ random
  • ใช้ list comprehension วนลูป ใช้ 'randrange' สุ่มเลขในช่วงที่กำหนด
  • กำหนดผลลัพธ์ให้ตัวแปร
  • แสดงผลลัพธ์บนคอนโซล