3

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

scott martin
  • 1,213
  • 1
  • 10
  • 25

4 Answers4

6

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']
Mayank Porwal
  • 31,737
  • 7
  • 30
  • 50
5

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']
khelwood
  • 52,115
  • 13
  • 74
  • 94
  • thanks for the reply. Could I please ask one more edit. What if I wanted to rename item1 as person and item2 as human. How could I modify your reply.. Thanks – scott martin Nov 26 '18 at 09:46
2

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)

Even for 100.000 Elements it seems to be slower to use numpy:

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)

MisterMonk
  • 287
  • 1
  • 9
1

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']
Kuldeep
  • 4,130
  • 6
  • 27
  • 52
Jagoda Gorus
  • 309
  • 4
  • 18