简体   繁体   English

从 csv 文件中索引多个字符

[英]Indexing a multiple characters from a csv file

I am attempting to index specific characters to their own variable, and I am only able to do this for 1 character.我试图将特定字符索引到它们自己的变量中,但我只能为 1 个字符执行此操作。

with open(fileName) as f:
    count1 = sum(l[0] == '1' for l in f)
    count2 = sum(l[0] == '2' for l in f)

print(count1)
print(count2)

This is my output这是我的 output

5 0 5 0

According to the values in the csv file, it should be:根据csv文件中的值,应该是:

5 4 5 4

I should mention, when I change the value from '1' to '2' in the first variable, it does give me 4, for some reason I cannot do both though.我应该提一下,当我将第一个变量中的值从“1”更改为“2”时,它确实给了我 4,但出于某种原因我不能同时执行这两个操作。

Well, once you've iterated over f once, f is exhausted.好吧,一旦你迭代了f一次, f就用完了。 That is, reading from it will return nothing.也就是说,从中读取不会返回任何内容。

There are basically 2 ways to fix this:基本上有两种方法可以解决这个问题:

1: open the file twice 1:打开文件两次

with open(fileName) as f:
    count1 = sum(l[0] == '1' for l in f)
with open(fileName) as f:
    count2 = sum(l[0] == '2' for l in f)

2: read the file into memory and use that 2:将文件读入 memory 并使用它

with open(fileName) as f:
    lines = f.readlines()

count1 = sum(l[0] == '1' for l in lines)
count2 = sum(l[0] == '2' for l in lines)

Which of the two you use is up to you.您使用两者中的哪一个取决于您。

(code is untested. might contain typos) (代码未经测试。可能包含拼写错误)

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

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