英文:
Python .ipynb file prints output to the terminal without print function .py doesnt
问题
我正在实现一个样本概率密度函数。尽管我的代码中没有打印函数,但它会从我的值中打印样本输出。我使用的是.ipynb文件,当我将代码复制到.py文件中时,就不会打印出来。我不明白问题出在哪里。以下是我的代码:
```python
import numpy as np
def gen_b():
samples = []
num_samples = 10000
while len(samples) < num_samples:
b = np.random.random() * 6
y = np.random.random()
if y <= pdf_b(b):
samples.append(b)
return samples
gen_b()
pdf_b(x)
是一个简单的 f(x) = y
函数,在其中没有打印函数。
我该如何解决这个问题?我不想让样本输出被打印出来。以下是我不想被打印的输出:
[2.140133171853366,
3.782237422460611,
4.252458824774285,
1.9767482772032179,
2.250855035249897,
4.788930465436959,
1.9076515188916072,
2.745557799097914,
3.620720920902893,
2.540311807348857,
3.3786579434452295,
4.654430681635432,
3.885627334171001,
3.03255430392689,
2.078660750831954,
1.563168692059776,
4.066738029089566,
4.173320782327262,
2.3957708748717117,
2.392456670794856,
2.0479422380490147,
3.0472011553416785,
1.2691569709730193,
2.930679937209872,
3.0627475835692044,
...
2.3660255564569264,
2.3079729976179957,
2.8430403284524752,
3.9573097908844583,
...]
<details>
<summary>英文:</summary>
I am implementing a sample probability density function. Although there is no print function in my code it prints sample output from my value. I use .ipynb file, and when i copy the code into .py file, it is not printed. I don't understand where is the problem. Here is my code:
import numpy as np
def gen_b():
samples = []
num_samples = 10000
while len(samples) < num_samples:
b = np.random.random() * 6
y = np.random.random()
if y <= pdf_b(b):
samples.append(b)
return samples
gen_b()
`pdf_b(x)` is a simple `f(x) = y` function, there is no printing function inside of it.
How can i solve the problem? I don't want to sample output is printed. Here is the output that I don't want to be printed:
[2.140133171853366,
3.782237422460611,
4.252458824774285,
1.9767482772032179,
2.250855035249897,
4.788930465436959,
1.9076515188916072,
2.745557799097914,
3.620720920902893,
2.540311807348857,
3.3786579434452295,
4.654430681635432,
3.885627334171001,
3.03255430392689,
2.078660750831954,
1.563168692059776,
4.066738029089566,
4.173320782327262,
2.3957708748717117,
2.392456670794856,
2.0479422380490147,
3.0472011553416785,
1.2691569709730193,
2.930679937209872,
3.0627475835692044,
...
2.3660255564569264,
2.3079729976179957,
2.8430403284524752,
3.9573097908844583,
...]
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
答案1
得分: 2
IPython是一个REPL,即一个读取、评估、打印循环。最后被评估的语句是gen_b()
,所以该值被打印出来。如果你不想打印它,你可以简单地将结果赋值给某个变量,即使是一个临时变量,_ = gen_b()
(或者在REPL中不运行它)。
英文:
IPython is a REPL, a read, evaluate, print loop. The last statement that is evaluated is gen_b()
, so the value is printed. If you don't want it printed, one thing you can do is to simply assign the result to something, even a throwaway variable, _ = gen_b()
(or just don't run it in a REPL).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论