I have a question reagarding my code, if anybody has some clues how to solve it. I need to write only one line of code, which outputs the line numbers of those lines that don´t include spaces between the words. My attempt was the following:
[line for line in range(len(open('test.txt').readlines())) if ' ' not in open('test.txt').readlines(line)]
I tried to use enumerate. But it didn`t work out as I intended. I would appreciate any clue on how to change my code, if anything of my code is correct.
The first step is to write your loop as a regular loop, then compress it into a list comprehension. What you have is:
lines = []
for line in range(len(open('test.txt').readlines()):
if ' ' not in open('test.txt').readlines(line):
lines.append(line)
Opening the file twice and using readlines()
is rarely the right way to solve a problem. Instead, it's usually better to iterate over each line, one at a time.
The wonderful enumerate()
function is a great way to get the index of elements as you iterate over them. It returns a tuple of (index, value)
for each input of a list, or other iterable.
With it, your loop can become something like this:
for num, line in enumerate(open('test.txt')):
if ' ' not in line:
lines.append(num)
Converting the loop into a list comprehension is left as an exercise for you.
This does it:
print([i for i,line in (enumerate(open("test.txt").readlines())) if " " not in line])
Content of example file:
apricot
a p p l e
mango
banana
che rry
Output:
[0, 2, 3]
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.