正确代码
时间: 2023-07-02 21:13:22 浏览: 29
以下是使用新列表的正确代码:
```python
lst = [34, 6, 7, 0, 0, 0, 9]
nonzero_lst = []
n = 0
for i in lst:
if i == 0:
n += 1
else:
nonzero_lst.append(i)
lst = nonzero_lst
print(n)
```
这段代码先遍历lst,如果元素为0,则将n加1;否则将元素加入新列表nonzero_lst中。最后将原列表lst赋值为非0元素的新列表nonzero_lst,并输出0的个数。这样就可以正确地删除所有的0,而不会影响遍历过程。
相关问题
怎么pycharm运行正确代码没结果显示
如果您在 PyCharm 中运行正确的代码没有结果显示,可能是因为您没有在代码末尾添加输出语句。请确保您的代码中包含适当的输出语句,例如 `print()`,以便您能够看到输出结果。另外,请确保您已经正确地配置了 PyCharm 的运行环境,并且您正在使用正确的解释器。如果您仍然遇到问题,请检查您的代码和 PyCharm 配置,并查看是否有任何错误或警告信息。
C plus plus codereview过程中,针对“文件处理时返回错误,检查文件是否关闭”,需要注意哪些检查点?请举代码一一说明。需要有错误代码示范和正确代码示范,并有示范代码的说明。
在 C++ 代码审查过程中,针对文件处理时返回错误,需要注意以下几点:
1. 检查文件是否正确打开:在使用文件之前,应该先检查文件是否正确打开,如果文件打开失败,应该立即返回错误。
示范代码(错误代码):
```c++
std::ofstream outfile("file.txt");
outfile << "Hello, World!";
```
正确代码示范:
```c++
std::ofstream outfile("file.txt");
if(!outfile)
{
std::cerr<<"file open failed"<<std::endl;
return -1;
}
outfile << "Hello, World!";
```
2. 检查文件是否关闭:在文件使用完毕后,应该及时关闭文件,如果文件未关闭,会导致资源泄露。
示范代码(错误代码):
```c++
std::ofstream outfile("file.txt");
outfile << "Hello, World!";
```
正确代码示范:
```c++
std::ofstream outfile("file.txt");
if(!outfile)
{
std::cerr<<"file open failed"<<std::endl;
return -1;
}
outfile << "Hello, World!";
outfile.close();
```
3. 检查文件访问权限,如果文件权限不够,需要检查是否有权限访问该文件。
示范代码(错误代码):
```c++
std::ofstream outfile("file.txt");
outfile << "Hello, World!";
```
正确代码示范:
```c++
std::ofstream outfile("
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)