python - CSV 文件读取问题(不使用 CSV 模块),程序没有提供输入选项
问题描述
我需要程序第一部分的帮助,我正在尝试创建一个条件, 如果所选国家/地区在数据文件中列出了一个省,则该条件将只为用户提供输入省的选项。例如,如果用户选择了未列出任何省份的奥地利,则不应提供该选项。但如果他们选择澳大利亚,那么它应该提示他们输入省份。
我不能使用 CSV 模块,因为我在 Uni 的课程还没有涵盖该模块,教授宁愿让我们应用基本的文件阅读概念。我真的不需要了,因为我已经有了主要的解决方案。
此文件中的数据示例如下:
province | country | 1/2/20 | 1/3/20 | 1/4/20|
--------------------------------------------------------------------
| Afghanistan| 0 | 1 | 2 |
| Albania | 0 | 0 | 1 |
Australian Capital Territory| Australia | 0 | 3 | 5 |
New South Wales | Australia | 4 | 5 | 6 |
| Austria | 0 | 3 | 4 |
(作为参考,我需要使用的数据是:https ://portland-my.sharepoint.com/:x:/g/personal/msharma8-c_ad_cityu_edu_hk/ES7eUlPURzxOqTmRLmcxVEMBRGlLq6REGHx0hs_bNilPTw?e=6Ybsmc )
但是,我的代码现在根本不提供省份的输入选项。
with open('covid19.csv', 'r') as f:
for line in f:
# this next line is not working ffs ahhh, it doesnt seem to understand what i need
if (country == line.split(',')[1]) and len(line.split(',')[0])>1:
while True:
province = raw_input('input a province/district here: ')
if province.lower() in province_list:
break
我也试过:
if (country == line.split(',')[1]) and (line.split(',')[0]) != '':
为了进一步参考,这里是整个代码块,我把它放在一个函数中:
with open('covid19.csv', 'r') as f:
country_list = []
province_list = []
date_list = ((f.readline().split(','))[4::])
date_list = [date[0:-2] for date in date_list if date[-4:]=='2020'] # to put all the dates in the same format
for line in f:
#list of all countries and provinces
province_list.append(line.split(',')[0].lower())
country_list.append(line.split(',')[1].lower())
while True:
country = raw_input("input a country here: ")
if country.lower() in country_list:
break
with open('covid19.csv', 'r') as f:
for line in f:
# this line is not working ffs ahhh, it doesnt seem to understand
if (country == line.split(',')[1]) and len(line.split(',')[0])>1:
while True:
province = raw_input('input a province/district here: ')
if province.lower() in province_list:
break
while True:
date = raw_input('input a date in m/d/yy: ')
if date in date_list:
print 'You have selected the date:',date
break
else:
print 'please enter a date in a valid format'
解决方案
您需要确保正确评估您的状况。
(country == line.split(',')[1]) and len(line.split(',')[0])>1
在 Python 中,and
具有比 更高的优先级>
,因此上面的行 Python 计算
(country == line.split(',')[1]) and len(line.split(',')[0])
然后判断结果是否大于 1。在 Python中True
和False
equate to 1
和0
分别,所以条件永远不会为真。
(country == line.split(',')[1]) and (len(line.split(',')[0]) > 1)
应该做你想做的。
推荐阅读
- javascript - 为什么我的幻灯片图像在淡入之前会短暂出现?
- c++ - Discrepancy in C++ between over-aligned struct and enum within container
- ios - 提交 iOS 应用时的非公开选择器
- python - 在pyqt5中的QTableWidget中高亮cellWidget
- paraview - 如何处理标志/异常值
- eclipse - Windows 和 Ubuntu 中 mpiexec 的不同行为
- django - 如何将 ManyToManyField 的选择数量限制为特定数量的选择
- c - 数组中的错误值
- android - ZIP 运算符不适用于 PublishSubject,我做错了什么?
- php - 在项目中仅包含一次 php 文件