简体   繁体   中英

AttributeError: 'generator' object has no attribute 'isdigit'

I'm trying to go through this file that I've created and only extract the ages of the people in the file. then take the average of the ages and print it out. I'm trying to iterate through the lines in the file and it says that the generator object has no attribute. I'm using python 3 and I commented out some code I was using before so I don't have to worry about it. I don't know if I should use the commented code either but I'm just scared of losing all the ideas I've gotten this far. How do I get those ages in my loop if I can't iterate through?

 f = open('myfile.txt','w') f.write('Name, Age, Gender, Profession\n') f.write('Harry, 23, Male, Software Engineer\n') f.write('Sam, 25, Male, Lawyer\n') f.write('Lisa, 29, Female, Computer Scientist\n') f.write('Mary, 22, Female, Doctor\n') f.close() # print(readFile.read()) # readFile = open("myfile.txt") with open('myfile.txt', 'r') as file: for line in file: values = (line.split(', ') for line in file) if values.isdigit[1] == True: numbers = 0 numbers += values average = numbers % 4 print(average)

Try:

f = open('myfile.txt','w')
f.write('Name, Age, Gender, Profession\n')
f.write('Harry, 23, Male, Software Engineer\n')
f.write('Sam, 25, Male, Lawyer\n')
f.write('Lisa, 29, Female, Computer Scientist\n')
f.write('Mary, 22, Female, Doctor\n')
f.close()

with open('myfile.txt', 'r') as file:
    numbers = 0
    for line in file:
        values = line.split(', ')
        if values[1].isdigit() == True:
            numbers += int(values[1])

    average = numbers / 4
    print(average) # 24.75

There are several issues:

  1. values = (line.split(', ') for line in file) assignes a generator to values , and a generator does not have isdigit . You are already using a for loop, so you don't need a generator (actually you shouldn't).

  2. In the corrected code, values now is a list of strings. So you need to use values[1] to access an item of the list, and then apply isdigit .

  3. You are resetting numbers in each iteration. Initiate the variable before the loop.

  4. values[1] is a string, so in order to add this to numbers , you need int .

  5. % is the modulus operator. Use / for division.

  6. Using a hard-coded number (in this case, dividing something by a specific number 4 ) is not a best option. You might want an alternative way to get the number of records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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