1

I have list :

 l = ['dataset/Frames_Sentence_Level/are you free today/5/free (3) 22.jpg','dataset/Frames_Sentence_Level/are you free today/6/free (3) 24.jpg','dataset/Frames_Sentence_Level/are you free today/7/free (3) 23.jpg']

Here I need output as the list consists of 5,6,7 from the list, that is

[5,6,7]

So for that I tried like below,

s= []
for i in l:  
  e = i.split('/')`
  s = e[3]
print(s)

when I print s inside the for loop, I am getting the output but if I print outside the loop the output is just 7. Please help me out

2
  • 2
    s.append(e[3])? you need to add items to the list, not reassign it every iteration. Commented May 10, 2022 at 10:04
  • e[3] == 7, so s = e[3] also makes s == 7. If you want to keep it a list append not reassign. Commented May 10, 2022 at 10:07

3 Answers 3

1

You can do this using a list comprehension and get strings…

l = ['dataset/Frames_Sentence_Level/are you free today/5/free (3) 22.jpg','dataset/Frames_Sentence_Level/are you free today/6/free (3) 24.jpg','dataset/Frames_Sentence_Level/are you free today/7/free (3) 23.jpg']
out_lst = [fname.split("/")[3] for fname in l]
print(out_lst)

# Output: [‘5’, ‘6’, ‘7’]

Or get integers…

l = ['dataset/Frames_Sentence_Level/are you free today/5/free (3) 22.jpg','dataset/Frames_Sentence_Level/are you free today/6/free (3) 24.jpg','dataset/Frames_Sentence_Level/are you free today/7/free (3) 23.jpg']
out_lst = [int(fname.split("/")[3]) 
           for fname in l]
print(out_lst)

# Output: [5, 6, 7]

I split the list comprehension across lines on the second one because we are doing a lot with the value. Seemed more clear to read.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this in just one line using list comprehension:

s = [i.split('/')[3] for i in l]

the s will contains your desired output.

Comments

0

The issue you are having is because you are replacing s with the value of e[3] within the loop rather than appending e[3] to the list s - try this:

s= []
for i in l:  
  e = i.split('/')`
  s.append(e[3]) # Note this change!
print(s)

While this should work as expected, it's worth noting Mehrdad Pedramfar's use of a comprehension is better for this kind of extraction, although for the uninitiated comprehensions can be difficult to read.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.