I have a list made of a python dictionary keys via; list(dict.keys())
.
dict.keys()
dict_keys(['South', 'North'])
I would like to add a string to the every element in the list = ['South', 'North']
like:
my_string = 'to_'
In the end I want to have list = ['to_South', 'to_North']
Is there a method I could use for this?
something like:
list.add_beginning_of_each_element('to_')
Or map
:
>>> l = ['South', 'North']
>>> list(map('to_'.__add__,l))
['to_South', 'to_North']
>>>
There a add_prefix
in pandas
, so if you have a pandas dataframe, you can just use add_prefix
to add to the columns, an example of making a dataframe out of a list and having them as columns:
>>> import pandas as pd
>>> pd.DataFrame(columns=['South', 'North']).add_prefix('to_').columns.tolist()
['to_South', 'to_North']
Use a list comprehension:
lst = ['South', 'North']
result = ['to_' + direction for direction in lst]
As an alternative you could use map:
def add_to_beginning(s, start='to_'):
return start + s
lst = ['South', 'North']
result = list(map(add_to_beginning, lst))
print(result)
You can use lambda function:
lst = ['South', 'North']
result = list(map(lambda x: 'to_' + x, lst))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With