Can anyone help me with a list comprehension to split a string into a nested list of words and characters? i.e:
mystring = "this is a string"
Wanted ouput:
[['t','h','i','s'],['i','s'],['a'],['s','t','r','i','n','g']]
I've tried the following, but it doesnt split 'x' into nested list:
mylist = [x.split() for x in mystring.split(' ')]
print(mylist)
[['this'],['is'],['a'],['string']]
[list(x) for x in mystring.split(' ')]
You can use a nested list comprehension:
[[j for j in i] for i in mystring.split()]
Yields:
[['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 't', 'r', 'i', 'n', 'g']]
You need list(x) instead of x.split():
[list(x) for x in mystring.split()]
Slightly similar to other answers
map(list,mystring.split(" "))
Related
l = ['hello', 'world', 'monday']
for i in range(n):
word = input()
l.append(word)
for j in l[0]:
print(j)
Output : h e l l o
I would like to do it for every word in l.
I want to keep my list intact because i would need to get len() of each word and i won't know the number of word that i could possibly get.
I don't know if i'm clear enough, if you need more informations let me know, thanks !
def split_into_letters(word):
return ' '.join(word)
lst = ['hello', 'world', 'monday']
lst_2 = list(map(split_into_letters, lst))
print(lst_2)
You can map each word to a function that splits it into letters
l = ['hello', 'world', 'monday']
list(map(list, l))
#output
[['h', 'e', 'l', 'l', 'o'],
['w', 'o', 'r', 'l', 'd'],
['m', 'o', 'n', 'd', 'a', 'y']]
from itertools import chain
lst = ['hello', 'world', 'monday']
# Print all letters of all words seperated by spaces
print(*chain.from_iterable(lst))
# Print all letters of all words seperated by spaces
# for each word on a new line
for word in lst:
print(*word)
I have list of lists consisting of chars and integers like this:
list = [[65], [119, 'e', 's', 'i'], [111, 'd', 'l'], [111, 'l', 'w'], [108, 'd', 'v', 'e', 'i'], [105, 'n'], [97, 'n'], ['111', 'k', 'a']]
I want to convert this into a single string like this:
"65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
I have tried this:
new_list = [' '.join(x for x in list)]
but it is giving me this error:
TypeError: sequence item 0: expected str instance, list found
So what am i supposed to do, I'm new to coding!
That error you get is because .join() expects strings to join together, but you are passing it a list instead (one of the subarrays).
A one liner would be:
" ".join(["".join([str(item) for item in sublist]) for sublist in your_list])
Note that this only works for one level of nested arrays. If you had more or indefinite, probably its better to write your own function that does the job.
To make it a bit easier to see what is happening you could use:
final_string = ""
for elem in list:
final_string = final_string + " "
for el in elem:
final_string = final_string +str(el)
You have ints in your sublists aswell, that need converting before joining. You can do the following, using map to do the string conversion of the tokens and str.join to piece them together:
lst = [[65], [119, 'e', ... ] # do NOT call a variable "list"
new_lst = " ".join("".join(map(str, sub)) for sub in lst)
# '65 119esi 111dl 111lw 108dvei 105n 97n 111ka'
Why is my code not working? I can't figure it out
matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
I am getting the error ValueError: list.remove(x): x not in list
EDIT:
first_list = ['i', 'am', 'an', 'old', 'man']
You want:
i.remove(j)
match_list is a list of lists
list_of_lists = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
first_list = ['i', 'am', 'an', 'old', 'man']
myList = []
for current_list in list_of_lists:
for item in current_list:
for word in first_list:
if item in word:
myList.append(item)
list_of_lists.remove(item)
I edited your code so it would read more sensibly, to me, so I can think I know what you're trying to do.
In my mind, you are reading through a list, from within a set of lists to check to see if an item from that "sublist" is in another list (first_list).
If the item is in one of the words in first list, you are trying to remove the "sublist" from list_of_lists, correct? If so, that's where you are getting your error. Say you are on the first iteration of the set of lists, and you are checking to see if the letter "i" from the first sublist in list_of_lists is in the first word from first_list. It should evaluate to true. At that point, you are then telling Python the following in plain english, "Python, remove the item from list_of_lists that has a value of i." However, because list_of_lists contains lists, that won't work, because none of the values within list_of_lists are strings, just lists.
What you need to do is specify the list you are currently iterating on, which will be represented by current_list in the above code.
So maybe instead of
list_of_lists.remove(item)
or rather in your code
match_list.remove(j)
try
list_of_lists.remove(current_list)
or rather in your code
match_list.remove(i).
I have a feeling you are going to experience other errors with the iterations that will likely remain in some scenarios if you get another match, but that's not the problem you're having now....
Try this:
btw: you used matchList and match_list in your post. I corrected that for my answer to make it consistent.
matchList = [['g', 'h', 'i'], ['a', 'b', 'c']]
myList = []
first_list = ['i', 'am', 'an', 'old', 'man']
for i in matchList:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
for s in myList:
if s in i:
i.remove(s)
print(myList)
['i', 'a', 'a', 'a']
print(matchList)
[['g', 'h'], ['b', 'c']]
You could try a list comprehesion after iteration.
matchList = [['g', 'h', 'i'], ['a', 'b', 'c']]
first_list = ['i', 'am', 'an', 'old', 'man']
myList = []
for i in matchList:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
# Remove items from sublists
matchList = [[j for j in matchList[i] if j not in myList] for i in range(len(matchList))]
Output:
In [7]: myList
Out[7]: ['i', 'a', 'a', 'a']
In [8]: matchList
Out[8]: [['g', 'h'], ['b', 'c']]
This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 2 years ago.
Is it possible to transform a string into a list, like this:
"5+6"
into
["5", "+", "6"]
list('5+6')
returns
['5', '+', '6']
Yes, very simply:
>>> s = "5+6"
>>> list(s)
['5', '+', '6']
Using map inbuilt list creation to work
Code:
map(None,"sart")
Output:
['s', 'a', 'r', 't']
You can also use list comprehension like:
lst = [x for x in "5+6"]
print(lst)
in python 3
you could make this ...
>>> s = 'bioinform'
>>> s
'bioinform'
>>> w = list(s)
>>> w
['b', 'i', 'o', 'i', 'n', 'f', 'o', 'r', 'm']
>>>
but if you give list any value will give you an error so you should restart your IDLE
This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 2 years ago.
Is there a function in python to split a word into a list of single letters? e.g:
s = "Word to Split"
to get
wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
The easiest way is probably just to use list(), but there is at least one other option as well:
s = "Word to Split"
wordlist = list(s) # option 1,
wordlist = [ch for ch in s] # option 2, list comprehension.
They should both give you what you need:
['W','o','r','d',' ','t','o',' ','S','p','l','i','t']
As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:
[doSomethingWith(ch) for ch in s]
The list function will do this
>>> list('foo')
['f', 'o', 'o']
Abuse of the rules, same result:
(x for x in 'Word to split')
Actually an iterator, not a list. But it's likely you won't really care.
text = "just trying out"
word_list = []
for i in range(len(text)):
word_list.append(text[i])
print(word_list)
Output:
['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']
The easiest option is to just use the list() command. However, if you don't want to use it or it dose not work for some bazaar reason, you can always use this method.
word = 'foo'
splitWord = []
for letter in word:
splitWord.append(letter)
print(splitWord) #prints ['f', 'o', 'o']
def count():
list = 'oixfjhibokxnjfklmhjpxesriktglanwekgfvnk'
word_list = []
# dict = {}
for i in range(len(list)):
word_list.append(list[i])
# word_list1 = sorted(word_list)
for i in range(len(word_list) - 1, 0, -1):
for j in range(i):
if word_list[j] > word_list[j + 1]:
temp = word_list[j]
word_list[j] = word_list[j + 1]
word_list[j + 1] = temp
print("final count of arrival of each letter is : \n", dict(map(lambda x: (x, word_list.count(x)), word_list)))