Python 如何向列表的每个值添加一个字符串,然后使该字符串的值累加?
我试图打印列表中的值并添加字符串。我想要一个值(我要添加的字符串中的colx)从0向上计数到列表的最后一个值Python 如何向列表的每个值添加一个字符串,然后使该字符串的值累加?,python,python-3.x,list,Python,Python 3.x,List,我试图打印列表中的值并添加字符串。我想要一个值(我要添加的字符串中的colx)从0向上计数到列表的最后一个值 #CODE list1 = ['dog' , 'cat', 'pig', 'cow'] for elem in list1: print(elem + ' = sheet.cell(r,colx).value') 电流输出: dog = sheet.cell(r,colx).value cat = sheet.cell(r,colx).value pig = sheet
#CODE
list1 = ['dog' , 'cat', 'pig', 'cow']
for elem in list1:
print(elem + ' = sheet.cell(r,colx).value')
电流输出:
dog = sheet.cell(r,colx).value
cat = sheet.cell(r,colx).value
pig = sheet.cell(r,colx).value
cow = sheet.cell(r,colx).value
期望输出:
dog = sheet.cell(r,0).value
cat = sheet.cell(r,1).value
pig = sheet.cell(r,2).value
cow = sheet.cell(r,3).value
为此,您可以打印出当前索引
list1 = ['dog' , 'cat', 'pig', 'cow']
for idx, elem in enumerate(list1):
print(elem + ' = sheet.cell(r,' ,idx , ').value')
如果您需要另一个startIndex:
list1 = ['dog' , 'cat', 'pig', 'cow']
startIndex = 2
for elem in list1:
print(elem + ' = sheet.cell(r,' ,startIndex , ').value')
startIndex = startIndex + 1
方法1:使用枚举
输出:
方法2:使用列表理解构建元组列表
输出:
您好,您可以轻松直接使用此代码 列表1=[“狗”、“猫”、“猪”、“牛”] 对于i,枚举中的元素(列表1):
打印({}=sheet.cell(r,{}).value'.format(elem,i+1))使用
打印(elem+'=sheet.cell(r,{colx}).value'.format(colx=colx))
谢谢!另外,如果我想在1或其他数字开始idx,我会怎么做呢?谢谢:)为此,只需将1
添加到idx
,就像print(elem+'=sheet.cell(r',idx+1',).value')
你可以像@codrelphi那样做。。。或者我更喜欢自己的计数变量。。我编辑我的答案
list1 = ['dog' , 'cat', 'pig', 'cow']
for index, elem in enumerate(list1):
print('{} = sheet.cell(r,{}).value'.format(elem, index+1)) # start counting from 1
dog = sheet.cell(r,1).value
cat = sheet.cell(r,2).value
pig = sheet.cell(r,3).value
cow = sheet.cell(r,4).value
list1 = ['dog' , 'cat', 'pig', 'cow']
list1_indexes = [(k, list1[k]) for k in range(0, len(list1))]
for list_item in list1_indexes:
print('{} = sheet.cell(r,{}).value'.format(list_item[1], list_item[0]+1))
dog = sheet.cell(r,1).value
cat = sheet.cell(r,2).value
pig = sheet.cell(r,3).value
cow = sheet.cell(r,4).value