简体   繁体   中英

Python: Simple Question regarding counting characters on a list of strings

this is a simple questions but I just cant get the following code to work in a loop. Outside the loop it works. Im sorry to bother with something so simple but Im learning Python:

Code in loop:

c=[]
for i in b:
  s=len(b[i])
  c.append(s)
c

I have also tried with "range(3)" instead of b for the loop header. The error I get is: "TypeError: object of type 'int' has no len()"

When I do the following (manually) it works great but I cant seem to use it on a loop:

s=len(b[1])
s

c=[]

ii=0
pa=len(b[ii])

c.append(pa)

I hope you can help me and once again Im sorry for the dumb question

Bro try enumerate, you are taking the variable i as the index of the list b. It contains the current value of b in the loop. you can either use enumerate or take a look at this code

c=[]
for i in b:
  s=len(i)
  c.append(s)

different from other languages ,i does not take index ,it takes value. you need to write following code

s=len(i)

Ex: b=[5,3,112] for i in b: print(i) output will be 5,3,112

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