Reputation: 1809
Could anyone help to improve my code? So, firstly. I've a list with one element. I need to make a new list that consists of duplicates of the element of the given list num times. However, some values for cloned elements such as id, name, fullname, login...must be different.
I'm writing code like this:
num = 5
list = list1
list1 = [copy.deepcopy(x) for item in list for x in repeat(item, num)]
for i, val in enumerate(list1):
list1[i]['account']['id'] = randint(2,10)
list1[i]['account']['name'] = 'name' + randint(2,10)
list1[i]['account']['FullName'] = 'statusName' + randint(2,10)
list1[i]['account']['login'] = 'login' + randint(2,10)
list1[i]['account']['contract']['id']= randint(2,10)
I wonder Is there any way to make it more efficient? I have the same task yet with much bigger list and it seems too many code lines for this...
thanks in advance
Upvotes: 0
Views: 73
Reputation: 18891
The important thing is to find the slowest part of the code and focus on that. I recommend using the cProfile
module, like this, and it will tell you which part of your code is the slowest:
import copy
import cProfile
def main():
# ...your earlier code goes here
num = 5
list = list1
list1 = [copy.deepcopy(x) for item in list for x in repeat(item, num)]
for i, val in enumerate(list1):
list1[i]['account']['id'] = randint(2,10)
list1[i]['account']['name'] = 'name' + randint(2,10)
list1[i]['account']['FullName'] = 'statusName' + randint(2,10)
list1[i]['account']['login'] = 'login' + randint(2,10)
list1[i]['account']['contract']['id']= randint(2,10)
if __name__ == "__main__":
cProfile.run("main()", sort="cumulative")
Upvotes: 1