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
Advertisement
Answer
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.