I have a python list as below:
['item1','item2','item3']
I am trying to rename the items in the list as
['person1','person2','person3']
Could anyone guide me. Thanks
I have a python list as below:
['item1','item2','item3']
I am trying to rename the items in the list as
['person1','person2','person3']
Could anyone guide me. Thanks
You can use replace
to change "item"
to "person"
, and you can use a list comprehension to generate a new list.
items = ['item1','item2','item3']
people = [item.replace('item', 'person') for item in items]
Result:
['person1', 'person2', 'person3']
If you want to replace specific elements by specific values, do this:
In [521]: items = ['item1','item2','item3']
In [522]: dic = {'item1':'person1', 'item2':'human', 'item3':'person3'}
In [523]: [dic.get(n, n) for n in items]
Out[523]: ['person1', 'human', 'person3']
With speed in mind and for a lot of elements:
%%timeit
arr = ['item1', 'item2', 'item3']
arr = np.char.replace(arr, 'item', 'person')
16.4 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
arr = ['item1', 'item2', 'item3']
arr = [x.replace('item', 'person') for x in arr]
1.42 µs ± 174 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Numpy: 177 ms ± 15.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
ListComprehension: 35.7 ms ± 3.15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Even Pandas.Series is slower on my tests:
%%timeit
series.str.replace('item', 'person')
144 ms ± 4.47 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
If there is only one digit at the end of basic list, you could use:
>>> out = []
>>> input = ['item1','item2','item3']
>>> for i in input:
out.append('person{}'.format(i[-1]))
>>> out
['person1', 'person2', 'person3']
EDIT:
I also came across this solution, which also works for numbers greater than 9:
>>> items = ['item1', 'item2', 'item3']
>>> out = []
>>> for item in items:
out.append('person{}'.format(int(filter(str.isdigit,item))))
>>> out
['person1', 'person2', 'person3']