简体   繁体   中英

I want print items in list one by one using list comprehension in python. How can do that?

itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]


print([f"Item {stock} : Price = {price}" for stock,price in itemlist]  )


for stock,price in itemlist:
  print(f"Item {stock} : Price = {price}")

how can i print list comprehension object one by one like for loop does?

I tried unpacking each item in list but couldn't able to do it.

how can unpack each item and print in a line by line format instead of of returing list.

i removed list and pyhton returns generator object how can i print that?

print(f"Item {stock} : Price = {price}" for stock,price in itemlist  )

Output : <generator object at 0x7fd0af2bc5d0>

Desired Output :

Item Tatamotors : Price = 483.4568

Item M&M : Price = 953.8045

Item TVSmotors : Price = 712

Item AshokLeyland : Price = 142.2567

Using LIST COMPREHENSION

itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]

print('\n'.join([f"Item {stock} : Price = {price}" for stock,price in itemlist]))  

Output:

Item Tatamotors : Price = 483.4568
Item M&M : Price = 953.8045
Item TVSmotors : Price = 712
Item AshokLeyland : Price = 142.2567

You can print using List Comprehension, but I think it'll occupy useless memory, In big scale environment it's not the best practice. But ya there is the way below,

itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]
    
# Dummy list, which is no use other that printing
[print(f"Item {stock} : Price = {price}") for stock,price in itemlist] 

Output:

Item Tatamotors : Price = 483.4568
Item M&M : Price = 953.8045
Item TVSmotors : Price = 712
Item AshokLeyland : Price = 142.2567

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM