Home > Net >  How to get a value of list from for loop in python?
How to get a value of list from for loop in python?

Time:05-10

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

CodePudding user response:

Try this in just one line using list comprehension:

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

the s will contains your desired output.

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

If you are a beginner in programming I would recommend the approach @SteJ are suggesting. At least you should understand this approach before trying out oneliners.

  • Related