Skip to content Skip to sidebar Skip to footer

How Can I Get The Nth Element Of String For List Of List In Python?

I have my txt file something like this. [0, 'we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n'] [1, 'I want to write a . I think I will.\n'] [2, '

Solution 1:

I guess what you are wanting is the string from each list. I am assuming you already would have a list of list parameter with each list from your text file. hence you can apply this to get the values.

list_of_strings = filter(lambda x:x[1], list_of_lists)

Solution 2:

You can try any of these method :

data=[[0, "we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n"],
[1, "I want to write a . I think I will.\n"],
[2, "@va_stress broke my twitter..\n"],
[3, "\" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry\n"],
[4, "aww great  "Picture to burn"\n"]]


print(list(map(lambda x:x[1].strip(),data)))

or

print([i[1].strip() for i in data])

output:

['we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....', 'I want to write a . I think I will.', '@va_stress broke my twitter..', '" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry', 'aww great  "Picture to burn"']

Solution 3:

Try this:

data=eval('['+(open('file.txt').read().replace('\n', ', ')[:-2])+']')
result=[]
for i indata:
    data.append(i[1])

The last 3 lines are pretty obvious, but here's what the first one does:

  1. open('file.txt').read() opens the file and gets the contents
  2. .replace('\n', ', ')[:-2] replaces the newlines with ,, except the last, so that it's formatted like a list. Skip [:-2]it if the last line doesn't end in a newline.
  3. '['+...+']' adds [ and ] for more formatting as a list.
  4. data=eval(...) makes creates the list and assigns it to data.

Just in case here is what the final lines do:

  1. empty list created and assigned to result
  2. i assigned to each value in data for the following line:
  3. appends the second value of each list within data to result.

Post a Comment for "How Can I Get The Nth Element Of String For List Of List In Python?"