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:
open('file.txt').read()
opens the file and gets the contents.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.'['+...+']'
adds[
and]
for more formatting as a list.data=eval(...)
makes creates the list and assigns it todata
.
Just in case here is what the final lines do:
- empty list created and assigned to
result
i
assigned to each value indata
for the following line:- appends the second value of each list within
data
toresult
.
Post a Comment for "How Can I Get The Nth Element Of String For List Of List In Python?"