Discuss Accessing the next element in the Python Programming forum on Dev Shed. Accessing the next element Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
Posts: 139
Time spent in forums: 2 Days 3 h 53 m 35 sec
Reputation Power: 2
Accessing the next element
Hello, i have a text file, say called 'Text.list' setup similar to the following:
element[1]
element[2]
element[3]
...
element[n]
i have the following code:
Code:
Text = open('Text.list','r').readlines()
for Line in Text :
# now i want to see if the current value of Line is equal to the
# next element in the file, ie. is Line == element[x+1]
Is there a slick way in Python to do this, without having to use a counter variable, etc?
Posts: 3,350
Time spent in forums: 1 Month 2 Weeks 3 Days 7 h 38 m 45 sec
Reputation Power: 383
zip is your friend. zip it!
Code:
#What do you mean by element? How does an "element" differ from Line?
#this code compares pairs of lines without counters, at some memory
#cost.
# the names curtail and behead come from the j definitions
# http://www.jsoftware.com
# curtail=: }:
# behead=: }.
def curtail(LIST):
'''
>>> curtail([1,2,3])
[1, 2]
'''
return LIST[:-1]
def behead(LIST):
'''
>>> behead([1,2,3])
[2, 3]
'''
return LIST[1:]
# preferred file use. Use the "with" statement.
with open('Text.list','r') as input_stream:
Text = input_stream.readlines()
# compare pairs of lines
for (LINE,NEXTLINE,) in zip(curtail(Text),behead(Text)):
if LINE == NEXTLINE:
print('duplicate adjacent lines of\n"{}"'.format(LINE))
__________________
[code]Code tags[/code] are essential for python code!
Posts: 35
Time spent in forums: 9 h 55 m 6 sec
Reputation Power: 1
The easiest way to do this without counter variables or loading the entire file into memory is to turn the check on its head. Rather than try and compare to the next line which you don't know, compare it to the previous line which you have already read.
Code:
lastline = None
with open('Text.list','r') as Text:
for Line in Text:
if Line == lastline:
# duplicate line found
print "Duplicate line: ",line
lastline = Line
Depending upon what you are trying to do this may not be practical but as it is only keeping two lines and a file pointer in memory it is very efficient.
Posts: 12
Time spent in forums: 4 h 37 m 41 sec
Reputation Power: 0
I am not sure if I understand the original question correctly. But if you are looking for unique entries in the file then you can use the "set" function and generators. Example below:
if __name__ == '__main__':
with open ("unsorted.txt", "r") as f:
x= list(set(line for line in f))
print x