某电视台要调查观众对该台8个栏目(设相应栏目编号为1~8)的受欢迎情况,,观众的投票情况已在“in.txt”文件中保存。使用数组进行编程,数组元素[1]对应电台栏目1,依次类推。统计输出电台各栏目的得票情况,并将结果保存至vote.txt 中
时间: 2023-08-31 16:36:47 浏览: 50
### 回答1:
好的,我可以为您提供代码示例。假设投票结果保存在`in.txt`文件中,每一行代表一位观众对8个栏目的投票情况,使用数字1-8表示不同的栏目,例如:
```
1 2 3 4 5 6 7 8
2 3 4 5 1 6 7 8
8 7 6 5 4 3 2 1
```
以下是实现代码:
```python
# 读取投票结果
with open('in.txt', 'r') as f:
lines = f.readlines()
# 初始化得票统计数组
votes = [0] * 8
# 统计得票数
for line in lines:
for i in range(8):
if line[i*2:i*2+1] == str(i+1):
votes[i] += 1
# 输出结果到文件
with open('vote.txt', 'w') as f:
for i in range(8):
f.write('栏目{}得票数:{}\n'.format(i+1, votes[i]))
```
运行完毕后,得票情况将保存在`vote.txt`文件中。
### 回答2:
将读取文件中的投票数据并存储到一个数组中,数组的下标对应着电视台栏目的编号。然后对数组中的每个元素进行累加得票数。统计完毕后,将结果输出到"vote.txt"文件中。
下面是代码示例:
```python
# 打开文件并读取投票数据
with open("in.txt", "r") as file:
vote_data = file.readlines()
# 初始化一个长度为9的数组,用于统计每个栏目的得票数(因为题目中栏目从1开始编号)
vote_count = [0] * 9
# 统计每个栏目的得票数
for vote in vote_data:
column_num = int(vote.strip())
vote_count[column_num] += 1
# 将结果写入文件"vote.txt"
with open("vote.txt", "w") as file:
for i in range(1, 9):
file.write(f"栏目{i}得票数:{vote_count[i]}\n")
```
这段代码会从文件"in.txt"中读取投票数据,然后统计每个栏目的得票数,并将结果写入到"vote.txt"文件中。最后的结果将显示每个栏目的得票数。
注意:此代码假设栏目编号从1到8,如果栏目编号是从0到7,请将"vote_count = [0] * 9"中的数字改为8。
### 回答3:
编程实现如下:
```python
# 读取投票情况文件
with open("in.txt", "r") as file:
votes = file.read().splitlines()
# 初始化栏目得票情况数组
vote_counts = [0, 0, 0, 0, 0, 0, 0, 0]
# 统计各栏目得票情况
for vote in votes:
program_number = int(vote)
vote_counts[program_number - 1] += 1
# 将结果保存至vote.txt文件
with open("vote.txt", "w") as file:
for i, count in enumerate(vote_counts):
file.write("栏目{}:{}票\n".format(i + 1, count))
```
以上代码首先读取了投票情况文件(in.txt),然后初始化一个长度为8的数组vote_counts用于统计各栏目的得票情况。
接下来使用一个循环遍历投票情况,每次将得到的投票数对应栏目的得票数加1。
最后,将得票情况写入vote.txt文件中,每行写入一个栏目的得票情况。
运行代码后,你可以在vote.txt文件中找到各栏目的得票情况。
相关推荐
![](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)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)