Python:变量初始化和for循环

时间:2015-11-16 12:57:50

标签: python list for-loop initialization

我有一个int的列表,范围从099,例如center_nodes=[51,52],我想执行一个简单的操作:

取第一个元素center_nodes[0],得到它的第一个数字first=str(center_nodes[0])[0],然后根据数字本身为其添加int

示例:如果first=5,则result=int(center_nodes[0])+int(first)。在这种情况下,它应该产生56

我写了一段代码来做这件事,但我总是得到0。我必须犯一些非常愚蠢的错误,我怀疑它是result变量的初始化,在脚本中称为grid_coord

我的尝试:

#code block to compute the center_nodes[] list
#here comes my script:
first=str(center_nodes[0])[0] #Get the first figure of element 0 of center_nodes
print('first figure: '+str(first))
grid_coord=None
if len(str(center_nodes[0]))==1: #Check if center_nodes[0] is in the 0-9 range
    grid_coord=int(first)
    print('Grid coord for center giant comp is: '+str(grid_coord))
elif len(str(center_nodes[0]))==2: #Check if center_nodes[0] is in the 10-99 range
    if first==1: #Checks the first digit of center_nodes[0] and then adds it to int(center_nodes[0])
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==2: #Check the second digit...
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==3: #Check the third digit...
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==4: #4th
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==5: #5th
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==6: #6th
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==7: #7th
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==8: #8th
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))
    if first==9: #9th and last
        grid_coord=int(center_nodes[0])+int(first)
        print('Grid coord for center giant comp is: '+str(grid_coord))

对于center_nodes=[51,52],我应该grid_coord=56,但我会得到grid_coord=0。我应该改变什么?

2 个答案:

答案 0 :(得分:2)

first=str(center_nodes[0])[0] #Get the first figure of element 0 of center_nodes
grid_coord=None
if len(str(center_nodes[0]))==1: #Check if center_nodes[0] is in the 0-9 range
    grid_coord=int(first)
    print('Grid coord for center giant comp is: '+str(grid_coord))
elif len(str(center_nodes[0]))==2: #Check if center_nodes[0] is in the 10-99 range
    grid_coord=int(center_nodes[0])+int(first)
    print('Grid coord for center giant comp is: '+str(grid_coord))

答案 1 :(得分:1)

如果我的理解是正确的,你需要像:

l = [51, 52, 83]

for item in l:
    newItem = int(str(item)[0]) + item
    print newItemt