我正在使用Python进行培训,在一个练习中,我应该打开一个文件.csv,并查找文件中有多少次在1950年至2000年之间的加利福尼亚州(“ CA”)中重复使用名称“ Max”。我完成了:
import csv
counter = 0
for line in file:
counter = counter + 1
line_splitted = line.strip().split(",")
if line_splitted[1] == "Max":
print(line_splitted)
输出的摘录(条目更多)是:
['17261', 'Max', '1965', 'M', 'AK', '6']
['20094', 'Max', '1983', 'M', 'AK', '5']
['20291', 'Max', '1984', 'M', 'AK', '5']
['20604', 'Max', '1986', 'M', 'AK', '10']
['20786', 'Max', '1987', 'M', 'AK', '10']
然后我写了:
if line_splitted[1] == "Max" and line_splitted[2] >= 1950 and line_splitted[2] <= 2000 and line_splitted[3] == "M" and line_splitted[4]== "CA":
print(line_splitted)
else:
continue
这是结果:
TypeError Traceback (most recent call last)
<ipython-input-53-d4b5d798cf33> in <module>
8 line_splitted = line.strip().split(",")
9 if line_splitted[1] == "Max":
---> 10 if line_splitted[1] == "Max" and line_splitted[2] >= 1950 and line_splitted[2] <= 2000 and line_splitted[3] == "M" and line_splitted[4]== "CA":
11 print(line_splitted)
12
TypeError: '>=' not supported between instances of 'str' and 'int'
[我知道我应该对Python说,将索引2上的条目转换为整数,但是我不知道该怎么做。而且,我怀疑我的解决方案太长了,无法提取所需的信息。非常感谢您的任何建议。
最简单的方法(例如,您的示例)可能是与字符串进行比较:
and line_splitted[2] >= "1950"
这样,您不必先转换为整数。
仅当所有这些字符串都恰好是4个字符长时,此方法才起作用。