我正在嘗試撰寫一種方法,在給定 Python 中的寬度和高度的情況下,在二維空間中生成并回傳 n 個隨機點我撰寫了一個演算法,但我想在系統中接收浮點數。這里我的代碼是:
import random
npoints = int(input("Type the npoints:"))
width = int(input("Enter the Width you want:"))
height = int (input("Enter the Height you want:"))
allpoints = [(a,b) for a in range(width) for b in range(height)]
sample = random.sample(allpoints, npoints)
print(sample)
Output is:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:8
[(8, 7), (3, 3), (7, 7), (9, 0)]
如何將它們列印為浮點數。例如: (8.75 , 6.31)
非常感謝您的幫助。
uj5u.com熱心網友回復:
更改a和b到float:
import random
npoints = int(input("Type the npoints:"))
width = int(input("Enter the Width you want:"))
height = int (input("Enter the Height you want:"))
# HERE ---------v--------v
allpoints = [(float(a),float(b)) for a in range(width) for b in range(height)]
sample = random.sample(allpoints, npoints)
print(sample)
輸出:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:8
[(1.0, 0.0), (8.0, 7.0), (5.0, 1.0), (2.0, 5.0)]
更新
我想要浮動,但您的解決方案只是這樣列印: 2.0 5.0
我們如何列印: 5.56 2.75 ?
列印 2 位小數:
>>> print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
(1.00, 0.00), (8.00, 7.00), (5.00, 1.00), (2.00, 5.00)
uj5u.com熱心網友回復:
首先你想float作為輸入。對于height和width更換int()用float()。
現在,您不能再在這些定義的框中生成所有點,因為浮點可以具有任意精度(理論上)。
所以你需要一種方法來分別生成坐標。0 & 之間的隨機 y 坐標height可以通過以下方式生成:
<random number between 0 to 1> * height
同樣的寬度。您可以使用random.random()0 到 1 之間的亂數。
完整代碼:
import random
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(sample)
輸出:
Type the npoints:3
Enter the Width you want:2.5
Enter the Height you want:3.5
[(0.7136697226350142, 1.3640823010874898), (2.4598008083240517, 1.691902371689177), (1.955991673900633, 2.730363157986461)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367541.html
下一篇:在物件中查找值,即在陣列中
