Question of Python second loop break and indexes

MRAB python at mrabarnett.plus.com
Wed May 9 05:13:00 EDT 2012


On 09/05/2012 09:36, lilin Yi wrote:
> //final_1 is a list of Identifier which I need to find corresponding
> files(four lines) in x(x is the file) and write following four lines
> in a new file.
>> //because the order of the identifier is the same, so after I find the
> same identifier in x , the next time I want to start from next index
> in x,which will save time. That is to say , when the if command
> satisfied ,it can automatically jump out out the second while loop and
> come to the next identifier of final_1 ,meanwhile the j should start
> not from the beginning but the position previous.
>> //when I run the code it takes too much time more than one hour and
> give the wrong result....so could you help me make some improvement of
> the code?
>> i=0
>> offset_1=0
>>> while i<len(final_1):
> 	j = offset_1
> 	while j<len(x1):
> 		if final_1[i] == x1[j]:
> 			new_file.write(x1[j])
> 			new_file.write(x1[j+1])
> 			new_file.write(x1[j+2])
> 			new_file.write(x1[j+3])
> 			offset_1 = j+4
> 			quit_loop="True"
> 		if quit_loop == "True":break
> 		else: j=j +1
> 	i=i+1

This is roughly equivalent:
j = 0
for f in final_1:
 try:
 # Look for the identifier starting at index 'j'.
 j = x1.index(f, j)
 except ValueError:
 # Failed to find the identifier.
 pass
 else:
 # Found the identifier at index 'j'.
 	new_file.write(x1[j])
 	new_file.write(x1[j + 1])
 	new_file.write(x1[j + 2])
 	new_file.write(x1[j + 3])
 	# Skip over the 4 lines.
 j += 4


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /