Can you help me optimize the code. This is in Python:
for fruit in fruit_list:
fruit_id = uuid.uuid4()
fruit_nos.append(TotalFruits(fruit_id, fruit))
(1) So there's a fruit list that contains a list of fruits
(2) For each fruit we generate a fruit_id using uuid
(3) We pass the fruit_id and the fruit to a class Total Fruits that returns the total number of fruits of that variety
(4) We append that to a fruit_nos list
I was trying to do list comprehensions but fruit_id = uuid.uuid4()
is becoming a problem. So, I would do:
fruit_nos = [TotalFruits(fruit_id, fruit) for fruit in fruit_list]
But of course, I'll miss the uuid part. Is there an efficient way to the code?
You can generate the uuid
within the comprehension:
fruit_nos = [TotalFruits(uuid.uuid4(), fruit) for fruit in fruit_list]
Note: uuid.uuid4()
returns a UUID object. If you need a string - try using the hex
attribute of that object: uuid.uuid4().hex
You can include fruit_id = uuid.uuid4()
inside the Class then you can use the list comp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.