my_list = ['cat','cow','dog','rabbit']
but what I want is to append/insert a character(or string) to one or more element(not all).
something like
my_list = ['cat','cow_%s','dog_%s','rabbit']%('gives milk','bark')
now updated list should look like
my_list = ['cat','cow_gives milk','dog_bark','rabbit']
one way is to do this is manually change/update the element one by one e.g my_list[2]=my_list[2]+"bark"
but I don't want that because my_list is long(around 100s element ) and 40+ need to be changed dynamically.
In my case It is like
my_list = ['cat','cow_%s','dog_%s','rabbit']
for a in xyz: #a is a string and xyz is a list of string
my_list=my_list%(a,a+'b')
fun(my_list)
You could do something like this:
changes = {"cow":"gives milk", "dog":"bark"}
my_list = [item if item not in changes else "_".join([item, changes[item]])
for item in my_list]
For greater efficiency if you will do this repeatedly, as JAB suggests in the comments, build a dictionary to map items to their locations (indices) in the list:
locations = dict((s, i) for i, s in enumerate(my_list))
You can then use this to find the corresponding items.
If you are stuck with the list of strings, some ending "%s"
, and list of things to put in them, I guess you will have to do something like:
for i, s in enumerate(my_list): # work through items in list with index
if s.endswith("%s"): # find an item to update
my_list[i] = s % xyz.pop(0) # update with first item popped from xyz
Note that xyz
will have to be a list for this, not tuple, as you can't pop
items from a tuple.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments