I have three lists and I want to concatenate each element from each list.
Here is what I tried:
quantity_list = ['6','4',7]
product_list = ['Apple','Orange','Grape']
uom_list = ['kg','kg','kg']
order_list = ""
order_list_temp = []
for ind,product in enumerate(product_list):
order_list_temp.append(product + "-"+quantity_list[ind])
for ind,uom in enumerate(uom_list):
order_list += order_list_temp[ind]+uom+"\n"
The expected output is:
Apple-6kg
Orange-4kg
Grape-7kg
It works as I expected but I want to know is there any other better solution.
You can use zip
:
>>> [f"{product}-{quantity}{uom}" for product, quantity, uom in zip(product_list, quantity_list, uom_list)]
['Apple-6kg', 'Orange-4kg', 'Grape-7kg']
Using list comprehension:
order_list = '\n'.join(
[ "{}-{}{}".format(p, q, u) for p, q, u in zip(product_list, quantity_list, uom_list) ]
)
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.