我正在用 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 个字符时才有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句