开发者

How to specify each index number - Python

开发者 https://www.devze.com 2023-03-28 20:44 出处:网络
I\'m writing th开发者_C百科is 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.

I'm writing th开发者_C百科is 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消