我正在從 csv 檔案中讀取數字,并嘗試每次在檔案的第一列中出現數字“1”時進行計數。
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)
這是我收到的錯誤:
TypeError: slice indices must be integers or None or have an __index__ method
uj5u.com熱心網友回復:
您不需要使用切片來執行此操作。如果一行中的第一個字符是,則為1True line[0] == 1。
您可以通過利用 python 將TrueandFalse視為的事實來簡單地對布林值求和1,并0允許您對諸如sum([True, True, False, 0, 1])which 求值之類的東西求和3
給定一個檔案path:
123
234
143
454
16786
111
你可以簡單地做:
with open(path) as f:
total = sum(l[0] == '1' for l in f)
print(total)
# prints: 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452123.html
