I have a list:
l = ['abc,def,ghi,jkl']
Now I want the result should be in the format abc, def, ghi,jkl as a separate element using python.
How do I do that?
I tried doing something else, but I am getting the result as 'a',b','c', etc.
Thanks in advance.
Use split function:
res = 'abc,def,ghi,jkl'.split(',')
Or:
l = ['abc,def,ghi,jkl']
output = []
for row in l:
output.extend(row.split(','))
# output will contain all the separate items for all items of l if more than one
print output
Not exactly sure what result you want:
>>> l = ['abc,def,ghi,jkl']
>>> l[0]
'abc,def,ghi,jkl'
>>> l[0].split(',')
['abc', 'def', 'ghi', 'jkl']
>>> ', '.join(l[0].split(','))
'abc, def, ghi, jkl'
A oneliner:
', '.join([ e for s in l for e in s.split(',') ])
'abc, def, ghi, jkl'
What you have as your example:
l = ['abc,def,ghi,jkl']
Is indeed a list, but a list with only one single item in it. This item is 'abc,def,ghi,jkl' The reason you only have one item in your list is because you created a string by starting with this character: ' and then everything that comes after that until you close the string with another ' is still the same string.
If you wanted to have four strings in your list, you should have written:
l = ['abc', 'def', 'ghi', 'jkl']
This gives you a list, here the first item is 'abc' and then the comma (,) tells the list constructor to treat the next object as another item, and so you get 'def' and so on....
Related
I was able to do it by looping accessing list[i][j]. but wanted to do it without looping.
Any ideas how to do it
Example list :
Input: ["abc","def","ghi"]
Output: ["$bc_","$ef_","$hi_"]
Use a list comprehension and concatenate or format the strings you want.
inlist = ['abc','def','ghi']
outlist = [f'${s[1:]}_' for s in inlist]
You can use list comprehension:
lstIn = ['abc', 'def', 'ghi']
lstOut = [f'${i[1:]}_' for i in lstIn]
print(lstOut)
Prints:
['$bc_', '$ef_', '$hi_']
Try this
lst = ["abc","def","ghi"]
out = [ "".join(("$",s[1:],"_")) for s in lst ]
Output: print(out)
['$bc_', '$ef_', '$hi_']
I have several strings like this:
mylist = ['pearsapple','grapevinesapple','sinkandapple'...]
I want to parse the parts before apple and then append to a new list:
new = ['pears','grapevines','sinkand']
Is there a way other than finding starting points of 'apple' in each string and then appending before the starting point?
By using slicing in combination with the index method of strings.
>>> [x[:x.index('apple')] for x in mylist]
['pears', 'grapevines', 'sinkand']
You could also use a regular expression
>>> import re
>>> [re.match('(.*?)apple', x).group(1) for x in mylist]
['pears', 'grapevines', 'sinkand']
I don't see why though.
I hope the word apple will be fix (fixed length word), then we can use:
second_list = [item[:-5] for item in mylist]
If some elements in the list don't contain 'apple' at the end of the string, this regex leaves the string untouched:
>>> import re
>>> mylist = ['pearsapple','grapevinesapple','sinkandapple', 'test', 'grappled']
>>> [re.sub('apple$', '', word) for word in mylist]
['pears', 'grapevines', 'sinkand', 'test', 'grappled']
By also using string split and list comprehension
new = [x.split('apple')[0] for x in mylist]
['pears', 'grapevines', 'sinkand']
One way to do it would be to iterate through every string in the list and then use the split() string function.
for word in mylist:
word = word.split("apple")[0]
I want to loop through a list of strings...
eg:
list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty']
I want to loop through the list items and search for the location of 'Hello!' within the string in each case an record its location.
Any ideas?
Use a list comprehension to collect the indexes of your wanted string:
>>> list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty', 'My Name is Josh']
>>> [s.find('Hello!') for s in list_of_strings]
[0, 0, 0, -1]
Note how the negative 1 shows that the final string does not contain the value you're looking for.
Use the string.find method.
>>> phrase = 'Hello, my name is Syko'
>>> phrase.find('Hello')
0
You could try list comprehensions
[(s, s.lower().index('hello')) for s in list_of_strings if s.lower() == 'hello']
>>> list_of_strings = ['Hello!, my name is Carl', 'Hello!, my name is Steve', 'Hello!, my name is Betty']
>>> indices = [position for position, phrase in enumerate(list_of_strings) if 'Hello!' in phrase]
>>> print indices
[0, 1, 2]
Using a comprehension list, loop over the list and check if the string has the Hello! string inside, if yes, append the position to the matches list.
Note: The enumerate build in brings you the index for each element in the list.
in case you are searching for multiple items in a list say Hello and name
find = lambda searchList, elem: [[i for i, x in enumerate(searchList) if x == e] for e in elem]
find(list_of_strings,['Hello','name'])
output is a list with the positions of the elements you are searching for in the order that you listed them
Given a list with several names as a parameter, I was wondering if there was a way to split the names by first and last and create a 2d list of all first names and all last names. For example given:
lst=(["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"])
the output should be:
[["Leonoardo","Brad","Angelina"],["DiCaprio","Pitt","Jolie"]]
I know that I need to iterate over the given list, and append the first names and last names to a new lists but I'm not quite sure how to go about it.
This is what I've got so far:
fname=[]
lname=[]
for i in nlst:
i.split()
fname.append(i[0])
lname.append(i[1])
return lname,fname
You can use a simple list comprehension:
>>> lst=(["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"])
>>> new = [[item.split(',')[1] for item in lst], [item.split(',')[0] for item in lst]]
>>> new
[['Leonardo', ' Brad', ' Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
Or you can zip it:
>>> x = [item.split(',') for item in lst]
>>> list(reversed(zip(*x)))
[('Leonardo', ' Brad', ' Angelina'), ('DiCaprio', 'Pitt', 'Jolie')]
This might help you:
list_names = []
list_last =[]
lst=["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]
for element in lst:
list_names.append(element.split(',')[0])
list_last.append(element.split(',')[1])
Let me know if you need anything else
a function to return the names after splitting.
def split_list(the_list=["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]):
list_2d = [[],[]]
for full_name in the_list:
first_name, second_name = full_name.split(',')
list_2d[0].append(first_name)
list_2d[1].append(second_name)
return list_2d
print split_list()
According your code, you can try this:
lst=(["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"])
fname=[]
lname=[]
for i in lst:
fname.append(i.split(",")[0])
lname.append(i.split(",")[1])
print [lname,fname]
You can split and transpose:
lst = ["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]
print([list(ele) for ele in zip(*(ele.split(",") for ele in lst))])
Or use map:
print(list(map(list, zip(*(ele.split(",") for ele in lst)))))
[['DiCaprio', 'Pitt', 'Jolie'], ['Leonardo', ' Brad', ' Angelina']]
If you need the order reversed:
print(list(map(list, zip(*(reversed(ele.split(",")) for ele in lst)))))
[['Leonardo', ' Brad', ' Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
For python2 you can use izip and the remove the list call on map:
from itertools import izip
print(map(list, izip(*(reversed(ele.split(",")) for ele in lst))))
You can use zip function :
>>> l=["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]
>>> zip(*[i.split(',') for i in l])[::-1]
[('Leonardo', ' Brad', ' Angelina'), ('DiCaprio', 'Pitt', 'Jolie')]
If you want the result as list you can convert to list with map function :
>>> map(list,zip(*[i.split(',') for i in l])[::-1])
[['Leonardo', ' Brad', ' Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
You could use a regex:
>>> re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst))
[('DiCaprio', 'Leonardo'), ('Pitt', 'Brad'), ('Jolie', 'Angelina')]
Then use either zip or map to transpose the list of tuples:
>>> map(None, *re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst)))
[('DiCaprio', 'Pitt', 'Jolie'), ('Leonardo', 'Brad', 'Angelina')]
On Python 3, you can't use map that way. Instead, you would do:
>>> list(map(lambda *x: [e for e in x], *re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst))))
Then reverse the order and make a list of lists rather than list of tuples if you wish:
>>> lot=map(None, *re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst)))
>>> [list(lot[1]), list(lot[0])]
[['Leonardo', 'Brad', 'Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
here all_sentences_2d is a list of lists, contains the list of sentences in each tweet:
all_sentences_2d = [['tweet_1_sentence_1', 'tweet_1_sentence_2'],['tweet_2_sentence_1', 'tweet_2_sentence_2']]
I want to append an empty sentence after the sentences of each tweet.
I mean I want all_sentences_2d to be like that:
all_sentences_2d = [['tweet_1_sentence_1', 'tweet_1_sentence_2', ''],['tweet_2_sentence_1', 'tweet_2_sentence_2', '']]
I used this list comprehension to do that:
all_sentences_2d = [tweet_sentences.append('') for tweet_sentences in all_sentences_2d]
but I got that:
all_sentences_2d = [None, None, None, None, None, None]
While debugging, I've seen the appending operation done correctly in the all elements but after that becomes all None. Any ideas?
list.append() updates the list in place and returns None. You can try this, though:
[tweet_sentences + [''] for tweet_sentences in all_sentences_2d]
Although I would prefer a plain for-loop here:
for v in all_sentences_2d:
v.append('')
You can use map:
>>> all_sentences_2d = [['tweet_1_sentence_1', 'tweet_1_sentence_2'],['tweet_2_sentence_1', 'tweet_2_sentence_2']]
>>> map(lambda l: l+[' '], all_sentences_2d )
[['tweet_1_sentence_1', 'tweet_1_sentence_2', ' '], ['tweet_2_sentence_1', 'tweet_2_sentence_2', ' ']]
Yes it can be done but you need to be careful of your syntax, you have your if statement in the wrong place for a start. Look at the example below, note that the list comprehension is NOT assigned to a variabe.
words = ['1', '12', '123', '1234']
shortest = []
longest = []
shortest_len = 3
[shortest.append(i) if len(i) <= shortest_len else longest.append(i) for i in words]