📜  Python – 产生 K 个均匀分布的浮点值

📅  最后修改于: 2022-05-13 01:55:30.324000             🧑  作者: Mango

Python – 产生 K 个均匀分布的浮点值

给定一个范围和元素 K,生成 K 个均匀分布的浮点值。

方法#1:使用循环

这是可以执行此任务的方式之一。在此,我们迭代直到 K,同时增加连续元素之间差异的计数器。

Python3
# Python3 code to demonstrate working of
# Produce K evenly spaced float values
# Using loop
  
# initializing range
i, j = 2, 10
  
# Initialize K
K = 15
  
# computing difference
diff = (j - i) / K
res = []
  
# using loop to add numbers to result
for idx in range(1, K + 1):
    res.append(i + (diff * idx))
  
# printing result
print("The constructed list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Produce K evenly spaced float values
# Using loop
  
# initializing range
i, j = 2, 10
  
# Initialize K
K = 15
  
# computing difference
diff = (j - i) / K
  
# using list comprehension to formulate elements
res = [i + (diff * idx) for idx in range(1, K + 1)]
  
# printing result
print("The constructed list : " + str(res))


输出

方法#2:使用列表推导

该方法的工作原理与上述方法类似。不同之处在于使用列表理解制定此解决方案的紧凑方式。

Python3

# Python3 code to demonstrate working of
# Produce K evenly spaced float values
# Using loop
  
# initializing range
i, j = 2, 10
  
# Initialize K
K = 15
  
# computing difference
diff = (j - i) / K
  
# using list comprehension to formulate elements
res = [i + (diff * idx) for idx in range(1, K + 1)]
  
# printing result
print("The constructed list : " + str(res))
输出