简体   繁体   中英

append adding contents to first list item, not adding new items to list

def gen(filename):
    result=[]
    with open(filename) as sample:
        for line in sample.read().splitlines():
            for ch in line.split():                
                result.append(ch)
                yield ch
return result

If i pass in "ABCDEF", i get ["ABCDEF"] back in result, instead of ["A","B","C","D","E","F"]

What could be the problem?

Also, am i using the generator correctly? If not, what am i doing wrong? I am close to grasping the concept, but i am not quite there yet and feel that adding a list might be making the generator counterproductive

EDIT: Here is how i am opening the file:

with filled_filename("ABCDEF") as fn:
        self.assertEqual(list(project.gen(f)), ["A","B","C","D","E","F"])
        print(list(project.gen(ff)))

I think this is what you want:

def gen(filename):
    with open(filename) as sample:
        for line in sample.read().splitlines():
            for ch in line:
                yield ch

# Example usage:
for ch in gen('myfile.txt'):
    print("Got character '{}'.".format(ch))

As you said, the list you're building up sort of makes the generator redundant. (You're yield ing each character as you go, but you're also returning the complete list , which is a pattern I've never seen before and probably not what you want to do.)

The main issue with your code, though, is that I think you want to split a line into individual characters, but line.split() doesn't do that. Just use for ch in line .

EDIT

Trying to get somewhere closer to your code:

def gen(filename):
    with open(filename) as sample:
        for line in sample:
            line = line.rstrip()
            for ch in line:
                yield ch

def filled_filename(text):
    with open('test.txt', 'wb') as f:
        f.write(text)
    return 'test.txt'

filename = filled_filename(b'ABCDEF')
assert list(gen(filename)) == ['A', 'B', 'C', 'D', 'E', 'F']

This code works and passes the assert.

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