简体   繁体   English

如何在列表的列表中多次索引某个字符?

[英]How do I index a certain character multiple times in a list of a list?

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.我正在从 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)

This is the error i receive:这是我收到的错误:

TypeError: slice indices must be integers or None or have an __index__ method

You don't need to do this with a slice.您不需要对切片执行此操作。 If the first character in a line is 1 then line[0] == 1 will be True.如果一行中的第一个字符是1 ,那么line[0] == 1将为 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您可以利用以下事实对布尔值进行简单求和:python 将TrueFalse视为1 ,而0允许您对sum([True, True, False, 0, 1])之类的东西求和,其计算结果为3

Given a file at path like:给定path中的文件,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM