I found a post asking about how to create whitespace in all list elements (Adding spaces to items in list (Python)), but I haven't found any posts asking about how to create whitespace in only specific elements of a list.
I'm wondering how to create a space between certain element characters in a list.
If I have a list like this:
lst = ['a', 'bb', 'c', 'bb']
How can I make a new list with a space between all 'bb' occurrences in a list to look like this?:
lst_new = ['a', 'b b', 'c', 'b b']
I've tried using .replace('bb', 'b" "b'), but I get 'b' and 'b' as separate list elements. Is there a specific notation for "whitespace" in Python? Or is there another way to approach this?
lst = ['a', 'bb', 'c', 'dd']
lst_new = []
for elem in lst:
if len(elem) > 1:
lst_new.append(' '.join(list(elem)))
else:
lst_new.append(elem)
print(lst_new)
Here's a very simple and easy to understand way to do it. The main idea is to check if the length of the elem is greater than 1, then use list to "split" the string. You can then join the string with a whitespace by using join.
Related
I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]
print('list length', len(lists))
splited=[]
splited1=lists[0][0].split(',')
print(splited1) #['a', 'b', 'c', 'h']
splited2=lists[1][0].split(',')
print(splited2) #['d', 'e', 'f', 'g']
listcomb=[splited1,splited2]
print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]
This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)
sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
print(sepcomb)
I'm having problems with splitting the letters and then joining them in a new list. Pls help
Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
to
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb.append(sep)
Method-2
sepcomb = list(i[0].split(',') for i in lists)
You can simply do the following:
final=[splinted1]+[splinted2]
Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]
Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]
listcomb = []
for each in lists:
splited = each[0].split(',')
listcomb.append(splited)
print(listcomb)
I want to know the quickest way to add single quotes to each element in a Python list created by hand.
When generating a list by hand, I generally start by creating a variable (e.g. my_list), assigning it to list brackets, and then populating the list with elements, surrounded by single quotes:
my_list = []
my_list = [ '1','baz','ctrl','4' ]
I want to know if there is a quicker way to make a list, however. The issue is, I usually finish writing my list, and then go in and add single quotes to every element in the list. That involves too many keystrokes, I think.
A quick but not effective solution on Jupyter NB's is, highlighting your list elements and pressing the single quote on your keyboard. This does not work if you have a list of words that you want to turn to strings, however; Python thinks you are calling variables (e.g. my_list = [1, baz, ctrl, 4 ]) and throws a NameError message. In this example, the list element baz would throw:
NameError: name 'baz' is not defined
I tried this question on SO, but it only works if your list already contains strings: Join a list of strings in python and wrap each string in quotation marks. This question also assumes you are only working with numbers: How to convert list into string with quotes in python.
I am not working on a particular project at the moment. This question is just for educational purposes. Thank you all for your input/shortcuts.
Yeah but then why not:
>>> s = 'a,b,cd,efg'
>>> s.split(',')
['a', 'b', 'cd', 'efg']
>>>
Then just copy it then paste it in
Or idea from #vash_the_stampede:
>>> s = 'a b cd efg'
>>> s.split()
['a', 'b', 'cd', 'efg']
>>>
The best way I found was:
>>> f = [10, 20, 30]
>>> new_f = [f'{str(i)}' for i in x]
>>> print(new_f)
['10', '20', '30']
You can take input as string and split it to list
For eg.
eg="This is python program"
print(eg)
eg=eg.split()
print(eg)
This will give output
This is python program
['This', 'is', 'python', 'program']
Hope this helps
It's been a while, but I think I've found a quick way following #U10-Forward's idea:
>>> list = ('A B C D E F G Hola Hello').split()
>>> print(list)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'Hola', 'Hello']
I have had to put items into a list but because I did not know how many items it would be I had to set the list up as
matching_words=["none"]*100
Once all the words have been added, I then want the remaining "none"'s to be removed so the list is only as long as the number of words added is. How can this be done. I tried this
newMatching_words=matching_words.remove("ABCDEFG")
print(newMatching_words)
This returned
None
You should have started with an empty list and appended items to it:
matching_words = []
for word in source_of_words:
matching_words.append(word)
print(matching_words)
Also, just so you know about the remove method:
print(matching_words)
matching_words.remove('bar')
print(matching_words)
Sample Output:
['foo', 'bar', 'baz']
['foo', 'baz']
There are some things which i want to explain when you need to define list length and when you don't.
First, you don't need to define list length at the beginning in
general case:
You can simply do :
#Just for example
new_list=[]
for i in map(chr,range(97,101)):
new_list.append(i)
print(new_list)
output:
['a', 'b', 'c', 'd']
Yes you need to define a empty list when you have another list for
index items like this:
matching_words=[None]*10
index_list=[4,3,1,2]
for i in zip(list(map(chr,range(97,101))),index_list):
matching_words.insert(i[1],i[0])
print(matching_words)
output:
[None, 'c', 'd', None, None, 'b', None, 'a', None, None, None, None, None, None]
['c', 'd', 'b', 'a']
In this program we have to insert chracter in that order in which the index_list showing the intergers , so if we try without defining list before then as you can see we are inserting first chr at index 4 which is not there.
In your case if you have second situation then try this to remove rest of none:
print([i for i in matching_words if i!='none'])
otherwise if you should go with first case.
I have a list of words but I need to take the last item off the list, perform a function with the rest of the list then replace the last item. But for some reason when i go to to replace the last item, it does this...
>>> List = ['this', 'is', 'a', 'list']
>>> last = List[-1]
>>> others = List[:-1]
>>> others += last
>>> print others
['this', 'is', 'a', 'l', 'i', 's', 't']
Is there any way I can concatenate the list called last onto others but have it just one single element.
Try using append
others.append(last)
You can further simplify the code by doing this:
last = List.pop()
This removes the last element or List if no parameter is specified, and saves it in the variable last for you
Use append instead of +=:
>>> others.append(last)
Use:
others.append(last)
instead of
others += last
This is because:
When you are doing
list += ["somethingHere"]
it's equivalent to
list.extend(["somethingHere"])
According to the doc,
list.extend(L) = Extend the list by appending all the items in the given list
but
list.append(x) = Add an item to the end of the list
And what you need here is to " add an item " not to " append all the items in the given list " (all characters in this case.)
Please use one following:
others += [last]
others.append(last)
+ for list instances is iterating over element being added to it, thus iterating over string you get list of characters.
others += 'string'
others += ['s', 't', 'r', 'i', 'n', 'g']
what I basically need is to check every element of a list and if some criteria fit I want to remove it from the list.
So for example let's say that
list=['a','b','c','d','e']
I basically want to write (in principle and not the actual code I try to implement)
If an element of the list is 'b' or 'c' remove it from the list and take the next.
But
for s in list:
if s=='b' or s=='c':
list.remove(s)
fails because when 'b' is removed the loop takes 'd' and not 'c' as the next element. So is there a way to do that faster than storing the elements in a separate list and removing them afterwards?
Thanks.
The easier way is to use a copy of the list - it can be done with a slice that extends "from the beginning" to the "end" of the list, like this:
for s in list[:]:
if s=='b' or s=='c':
list.remove(s)
You have considered this, and this is simple enough to be in your code, unless this list is really big, and in a critical part of the code (like, in the main loop of an action game). In that case, I sometimes use the following idiom:
to_remove = []
for index, s in enumerate(list):
if s == "b" or s == "c":
to_remove.append(index)
for index in reversed(to_remove):
del list[index]
Of course you can resort to a while loop instead:
index = 0
while index < len(list):
if s == "b" or s == "c":
del list[index]
continue
index += 1
Its better not to reinvent things which are already available. Use filter functions and lambda in these cases. Its more pythonic and looks cleaner.
filter(lambda x:x not in ['b','c'],['a','b','c','d','e'])
alternatively you can use list comprehension
[x for x in ['a','b','c','d','e'] if x not in ['b','c']]
This is exactly what itertools.ifilter is designed for.
from itertools import ifilter
ifilter(lambda x: x not in ['b', 'c'], ['a', 'b', 'c', 'd', 'e'])
will give you back a generator for your list. If you actually need a list, you can create it using one of the standard techniques for converting a generator to a list:
list(ifilter(lambda x: x not in ['b', 'c'], ['a', 'b', 'c', 'd', 'e']))
or
[x for x in ifilter(lambda x: x not in ['b', 'c'], ['a', 'b', 'c', 'd', 'e'])]
If you are ok with creating a copy of the list you can do it like this (list comprehension):
[s for s in list if s != 'b' and s != 'c']