python怎么将每次函数的返回值写入一个数组
时间: 2024-05-01 18:16:55 浏览: 104
可以使用一个空数组来存储每次函数的返回值,然后在函数中将返回值添加到数组中。以下是一个示例代码:
```python
def my_function(num):
return num * 2
results = [] # 创建空数组
for i in range(5):
result = my_function(i)
results.append(result) # 将返回值添加到数组中
print(results) # 输出结果:[0, 2, 4, 6, 8]
```
在上面的例子中,我们定义了一个函数`my_function`,它会将传入的参数乘以2并返回。我们创建了一个空数组`results`,然后使用一个循环来多次调用`my_function`,并将每次返回的值添加到`results`数组中。最后,我们输出了`results`数组的值。
相关问题
python将函数的返回值写入文本框控件里
可以使用以下代码将函数的返回值写入文本框控件中:
```
text_box.insert('end', str(function_name()))
```
其中,`text_box` 是文本框控件的名称,`function_name()` 是需要返回值的函数名称。`str()` 函数将返回值转换为字符串类型,以便在文本框中显示。
1.编写函数writelistolfile(strlistfilename): 形参说明:strlist:字符型列表,每个元素都是字符串,如slist=[“asd”,”:sdfff”,"ghjjj] filename:带路径的文件名,如:在d:lexifiles.txt函数返回值:无 函数功能:将列表strlist元素写入文件d:lexlfilestxt中,每个元素占一行。 函数实现后调用函数测试其正确性。如:writelistolfile(slist). 2.编写函数 deletedirs( path): 形参说明:path是一个文件夹绝对路径,函数返回值:无 函数返回值:将path文件夹包括子文件夹内所有文件和文件夹全部删除。 将2.zip解压缩到d:ltemp文件中,调用函数测试其正确性。如:deletedirs(r”d:\temp”).
以下是两个函数的实现代码:
1. writelistolfile 函数:
```python
def writelistolfile(strlist, filename):
with open(filename, 'w') as f:
for s in strlist:
f.write(s + '\n')
```
2. deletedirs 函数:
```python
import os
def deletedirs(path):
if os.path.exists(path):
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(path)
```
调用方式如下:
```python
# 测试 writelistolfile 函数
slist = ["asd", ":sdfff", "ghjjj"]
filename = r"d:\lexifiles.txt"
writelistolfile(slist, filename)
# 测试 deletedirs 函数
path = r"d:\temp\2"
deletedirs(path)
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)