简体   繁体   中英

How to specify each index number - Python

I'm writing this program that is supposed to convert binary to hex. I have to use the for loop. The part I need is how do I get the program to get the integer and its index number.

my code so far

q = raw_input('asdf ')
p = list(q)
t = [int(x) for x in p]
for i in t:
    if i == 1:
    w=i*(2**(3-t[x]))
    print w

the t[x] part is supposed to be the index number. So what is happening is if its a one then it will multiply by 2^3-(its index number)

How do I refer to the index number?

And how do I get it to sum all the values it gets

You can use the enumerate function.

for rank, item in enumerate(my_list):
   # here you have the index of the item (rank)
   # and the item ( the same as my_list[rank] )

for your example you can do something like this :

 inital_binary = raw_input("polop")
 for rank, letter in enumerate(inital_binary):
    print int(letter) * 2**(len(inital_binary) - (rank+1))

that will give for an input of 1100 :

8
4
0
0

Try this:

for ind in range(len(t)):
  i = t[ind]
  ...

Then i is the variable you had before, and ind is the loop number.

For the sum, do:

result = 0

before the loop, and

  result += w

inside the loop.

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