2

I have this line of code, it puts the english words in a text line (in this case archer and bowman) into a list and uses the integer of the number of words (02 in this case) to figure out how many words are in the line

line = 09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000 ~ 10290474 n 0000 ~ 10718145 n 0000
L = line.split()
word = L[4:4 + 2 * int(L[3]):2]
print(word)

This prints out ['archer', 'bowman']

I want to use the line of code that assigns the words to a list in another way, i want to assign the 8 digit numbers that appear after the '@' symbol to a different list.

I have got the code that gets the amount of 8 digit numbers in the file and my efforts so far. (the number of 8 digit figures in this case is 003)

pointer_num = re.findall(r'\b\d{3}\b', line)
K = int(pointer_num[0])
before_at, after_at = line.split('@')
S = after_at.split()[0:0 +3 * K:3]

S should be the list of 8 digit figures. although this code prints S out as:

['09640897', '~', '0000']

This is the right number of entries, just the wrong ones. If someone could explain word = L[4:4 + 2 * int(L[3]):2] I should be able to correct it myself

2 Answers 2

4

L[4:4 + 2 * int(L[3]):2] can be understood like this:

L[3] returns the fourth element in the list L (e.g. '02').

int(L[3]) returns the int of the string, L[3] (e.g. 2).

4 + 2 * int(L[3]) returns an int, e.g. 4+2*2=8.

L[4:8:2] returns a list consisting of the elements L[4] through L[7], skipping by 2. In other words, [L[4], L[6]]. In general L[start:stop:skip] returns a list which starts with L[start], and ends just before L[stop]. Think of [start, stop) as a half-open interval. The last number skip, causes the list to skip by this number of elements.

The complete rules on how Python slicing works for sequence types are explained in Notes 3,4,5 here.

1
  • S = after_at.split()[0:0 +4 * K:4] this works now! excellent
    – Johnnerz
    Jun 13, 2013 at 10:41
1

L[3] is 02.

int(L[3]) is 2

4 + 2 * int(L[3]) is 8

L[4:4 + 2 * int(L[3]):2] is L[4:8:2] which means items of L from index 4 included up to index 8 excluded, with steps of 2

L[4] is 'archer' and L[6] is 'bowman'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.