Vivek Singh
Vivek Singh

Reputation: 33

Replace the particular value of array by some other value using python for loop

staff_text=['31','32']
staffing_title = ['14','28','14','20']

I have two array like above.and i want output like

staffing_title = ['31','28','32','20']

So basically whenever 14 comes in staffing_title array it replace by staff_text values.

ex if first 14 comes replace by 31,When second 14 comes replace by 32 and so on

Upvotes: 0

Views: 31

Answers (2)

akash karothiya
akash karothiya

Reputation: 5950

Here is the one liner using list comprehension :

>>> staffing_title = ['14', '28', '14', '20']
>>> staff_text=['31','32']

>>> res = [staff_text.pop(0) if item == str(14) else item for item in staffing_title ]
>>> print(res)
['31', '28', '32', '20']   

Upvotes: 1

NPE
NPE

Reputation: 500357

The following will do it:

>>> [t if t != '14' else staff_text.pop() for t in staffing_title]
['32', '28', '31', '20']

Note that this modifies staff_text, so you might want to make it operate on a copy.

This code assumes that there are at least as many elements in staff_text as there are '14' strings in staffing_title (but then you don't specify what should happen if there aren't).

Upvotes: 0

Related Questions