List of Strings to Strings - python

How can I turn this
list = [['I','am','a','hero'],['What','time','is','it']]
to this
list = [["I am a hero"],["What time is it"]]
This doesn't work:
list(chain.from_iterable(list.str.split(',')))
And neither does:
[a for a in list]

You could join the list items:
list1 = [['I', 'am', 'a', 'hero'], ['What', 'time', 'is', 'it']]
list2 = [[' '.join(item)] for item in list1]
print(list2)
Output:
[['I am a hero'], ['What time is it']]

Here is one way of doing it
lst = [['I','am','a','hero'],['What','time','is','it']]
new_list = [[' '.join(x)] for x in lst]
print(new_list)

Related

Split The Second String of Every Element in a List into Multiple Strings

I am very very new to python so I'm still figuring out the basics.
I have a nested list with each element containing two strings like so:
mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]
I would like to iterate through each element in mylist, and split the second string into multiple strings so it looks like:
mylist = [['wowza', 'Here', 'is', 'a', 'string'],['omg', 'yet', 'another', 'string']]
I have tried so many things, such as unzipping and
for elem in mylist:
mylist.append(elem)
NewList = [item[1].split(' ') for item in mylist]
print(NewList)
and even
for elem in mylist:
NewList = ' '.join(elem)
def Convert(string):
li = list(string.split(' '))
return li
print(Convert(NewList))
Which just gives me a variable that contains a bunch of lists
I know I'm way over complicating this, so any advice would be greatly appreciated
You can use list comprehension
mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]
req_list = [[i[0]]+ i[1].split() for i in mylist]
# [['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]
I agree with #DeepakTripathi's list comprehension suggestion (+1) but I would structure it more descriptively:
>>> mylist = [['Wowza', 'Here is a string'], ['omg', 'yet another string']]
>>> newList = [[tag, *words.split()] for (tag, words) in mylist]
>>> print(newList)
[['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]
>>>
You can use the + operator on lists to combine them:
a = ['hi', 'multiple words here']
b = []
for i in a:
b += i.split()

Removing strings from a list dependent on their length?

I am trying to remove any strings from this list of strings if their length is greater than 5. I don't know why it is only removing what seems to be random strings. Please help. The item for sublist part of the code just changes the list of lists, into a normal list of strings.
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist]
var=0
for words in li:
if len(li[var])>5:
li.pop()
var+=1
print(li)
The output is: ['name', 'number', 'continue', 'stop', 'signify']
Just include the check when flattening the list:
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist if len(item) <= 5]
['name', 'stop', 'racer']
You can use a list comprehension to build a new list with only items that are 5 or less in length.
>>> l = ['123456', '123', '12345', '1', '1234567', '12', '1234567']
>>> l = [x for x in l if len(x) <= 5]
>>> l
['123', '12345', '1', '12']
list(filter(lambda x: len(x[0]) <= 5, list2))

Find List2 in List1 at starting Position

List1 = ['RELEASE', 'KM123', 'MOTOR', 'XS4501', 'NAME']
List2 = ['KM', 'XS', 'M']
Now I am using code that only searches List2 in List1 in any position.
Result = [ s for s in List1 if any(xs in s for xs in List2]
Output :
[KM123', 'MOTOR', 'XS4501', 'NAME']
But I don't want 'NAME' to be in the list because it contains 'M' not in the starting. Any help...
Use str.startswith() which checks if a string starts with a particular sequence of characters:
[s for s in List1 if any(s.startswith(xs) for xs in List2)]
Looks like you can use str.startswith
Ex:
List1 = ['RELEASE', 'KM123', 'MOTOR', 'XS4501', 'NAME']
List2 = ('KM', 'XS', 'M') #convert to tuple
result = [ s for s in List1 if s.startswith(List2)]
print(result) #-->['KM123', 'MOTOR', 'XS4501']

Python list in list with 2 strings

I have 2 lists of strings. I would like to combine them together to create list in lists like this one below.
[['Hello','praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
How to do it? Somehow create instance of list in list or there is some "python magic"?
Thank you
zip (Python Docs) is what you are looking for. You can stitch together two lists in a list comprehension:
l1 = ['Hello', 'world']
l2 = ['praet:sg:m1:perf','subst:pl:acc:n']
zipped = [list(items) for items in zip(l1,l2)]
print(zipped)
Result:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
There are many ways to do that.
ex-1: by using '+'
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
print([list1]+[list2])
ex-2: by using append()
res =[]
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
res.append(list1)
res.append(list2)
print(res)
ex-3: by using zip()
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
res = [[l1, l2] for l1,l2 in zip(list1, list2)]
print(res)
I hope this helps:
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
newlist = []
for i in range(len(list1)):
newlist.append([list1[i],list2[i]])
Just add the two list you have to another list:
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']
result = [list1, list2]
Another way:
result = []
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']
...
result.append(list1)
result.append(list2)
Use zip
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
result = [[x, y] for x,y in zip(list1, list2)]
print(result)
Output:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]

Get first element of a string sublist as a dictionary key with a list of value in python

So I have a list of strings. I need to convert the first part of the string to a key in a dictionary and treat the remaining part as the value. E.G the list is:
['We have a nice weekend','Hope you all well']
It should return:
{'We':['have','a','nice','weekend'],'Hope':['you','all','well']}
My attempt is the following:
dict1 = {}
dict1 = {item[0]:item[1:] for item in List1}
return dict1
But this give me a result of:
{'W':'e have a nice weekend','H':'ope you all well'
How to fix it? Thanks in advance.
You can try this.
lines=['We have a nice weekend','Hope you all well']
d={}
for line in lines:
k,*v=line.split()
d[k]=v
d
# {'We': ['have', 'a', 'nice', 'weekend'], 'Hope': ['you', 'all', 'well']}
Try this:
x = ['We have a nice weekend','Hope you all well']
then:
y = {s[0]:s[1:] for s in (p.split() for p in x)}
Then y is:
{'We': ['have', 'a', 'nice', 'weekend'],
'Hope': ['you', 'all', 'well']}
Try the following :
list1 = ['We have a nice weekend', 'Hope you all well']
# convert a string into list of words separated by a space
list1 = [item.split(' ') for item in list1]
print(list1) # [['We', 'have', 'a', 'nice', 'weekend'], ['Hope', 'you', 'all', 'well']]
dict1 = {item[0]: item[1:] for item in list1}
print(dict1) # {'We': ['have', 'a', 'nice', 'weekend'], 'Hope': ['you', 'all', 'well']}
Replace your 2nd line:
dict1 = {item[0]:item[1:] for item in List1}
with this:
dict1 = {item.split()[0]:' '.join(item.split()[1:]) for item in List1}
You can use map to split each string in the list and unpacking to separate the first word from the rest:
strings = ['We have a nice weekend','Hope you all well']
result = { k:v for k,*v in map(str.split,strings) }
output:
print(result)
{'We': ['have', 'a', 'nice', 'weekend'], 'Hope': ['you', 'all', 'well']}

Categories