python - Gathering every other string from list / line from file -


i have been scripting around 2 weeks, , have learnt reading file.

what want every other entry original list , store in new list. best way it?

with open("test.txt",mode="r") myfile: file = myfile.read().splitlines()  username = []  in range (len(file)):     if file.index(file[i])%2 == 0 or file.index(file[i]) == 0:         username.append(file[i]) print(username) 

please bear in mind have studied python around ten hours far - i'm quite happy seemed work.

there @ least couple ways accomplish same thing less code.

slice notation

python has way of iterating on every nth element of array called slice notation. can replace entire loop following line

username.extend(file[0::2]) 

what means grab every 2nd element starting @ index 0 , add username array.

the range() function

you can use different version of range() function, allows specify start, end , step, list so.

for in range(0, len(file), 2):     username.append(file[i]) 

the range() function documented here.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -