อยากจะนับรอบ ของ loop for in ทำยังไงได้บ้างค่ะ

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: อยากจะนับรอบ ของ loop for in ทำยังไงได้บ้างค่ะ

Re: อยากจะนับรอบ ของ loop for in ทำยังไงได้บ้างค่ะ

โดย thatsawan » 21/07/2017 1:07 pm

อีกหนึ่ง วิธี

โค้ด: เลือกทั้งหมด

i = 0
fruits = ['banana', 'apple',  'mango']
for index in fruits:
	i = i +1
   print i

Re: อยากจะนับรอบ ของ loop for in ทำยังไงได้บ้างค่ะ

โดย nuattawoot » 21/07/2017 12:10 pm

โค้ด: เลือกทั้งหมด

fruits = ['banana', 'apple',  'mango']
print 'Current fruit :', len(fruits)
ผลที่ได้ Current fruit : 3
---------------------------------------------------------------

โค้ด: เลือกทั้งหมด

fruits = ['banana', 'apple',  'mango']
for i,e in enumerate(fruits,start=1):
    print('%d:%s'%(i,e))
ผลที่ได้
1:banana
2:apple
3:mango

อยากจะนับรอบ ของ loop for in ทำยังไงได้บ้างค่ะ

โดย thatsawan » 21/07/2017 12:00 pm

โค้ด: เลือกทั้งหมด

fruits = ['banana', 'apple',  'mango']
for index in fruits:
   print 'Current fruit :', fruits
จะเอาไว้ดักค่า

ลองใส่ i++ มัน error
ลองใส่ index ก้อยังไม่ถูกที่จะเอาไปใช้ ค่ะ

ข้างบน