简体   繁体   中英

printing an increasing number along with the items of a list in python

I have a list in python - ['item1','item2','item3','item4'] . I am trying to print this list in following way - 1. ITEMS: item1 2. ITEMS: item2 3. ITEMS: item3 4. ITEMS: item4 . I wrote this code but this is giving error as I am trying to specify range() in wrong way:

list_semi = ["%d. ITEMS: %s" % (x for x in range(1,len(bookings)),items) for items in bookings]
print('Your items are {}.'.format(','.join(list_semi)))

bookings in the above code is the list whose sample data I have posted above. How can I print the list in the desired way as I have mentioned above?

UPDATE CASE 2 If my sample input list changes to - [[item1,price1],[item2,price2]...] and I want the sample output as 1. ITEMS: item1, PRICE: price1 2. ITEMS: item2, PRICE: price2 3. ITEMS: item3, PRICE: price3 4. ITEMS: item4, PRICE: price4 then how should I frame my code? the list name is same as bookings

No need to use range . Iterate on the list object directly, using enumerate to generate the indices. Specify the start parameter as 1:

>>> ' '.join(['{}. ITEMS: {}'.format(i, x) for i, x in enumerate(lst, 1)])
'1. ITEMS: item1 2. ITEMS: item2 3. ITEMS: item3 4. ITEMS: item4'

Update :

>>> lst = [['item1','price1'],['item2','price2']]
>>> ' '.join(['{}. ITEMS: {}, PRICE: {}'.format(i, *x) for i, x in enumerate(lst, 1)])
'1. ITEMS: item1, PRICE: price1 2. ITEMS: item2, PRICE: price2'

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