I am reading in numbers from a csv file and attempting to count each time the number '1' occurs in the first column of the file.
f = open(fileName, 'r')
reader = csv.reader(f)
votes = []
count = 0
for row in reader:
votes.append(row)
for i in votes:
if votes[0:i] == '1':
count = 1
print(count)
This is the error i receive:
TypeError: slice indices must be integers or None or have an __index__ method
CodePudding user response:
You don't need to test with a slice. If the first character in a line is 1
then line[0] == 1
will be True.
You can simple sum the booleans by taking advantage of the fact that python treats True
and False
as 1
, and 0
allowing you to sum things like sum([True, True, False, 0, 1])
which evaluates to 3
Given a file at path
like:
123
234
143
454
16786
111
You can simply do:
with open(path) as f:
total = sum(l[0] == '1' for l in f)
print(total)
# prints: 4
CodePudding user response:
Your second loop needs to be like this
for i in votes:
if '1' in i:
count = 1