gpt4 book ai didi

python - 如何向列表的每个值添加一个字符串,然后将该字符串的值加起来?

转载 作者:行者123 更新时间:2023-11-28 20:54:48 25 4
gpt4 key购买 nike

我正在尝试打印列表中的值并添加字符串。我想要一个值(我添加的字符串中的 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.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

最佳答案

Method 1: using enumerate

list1 = ['dog' , 'cat', 'pig', 'cow']
for index, elem in enumerate(list1):
print('{} = sheet.cell(r,{}).value'.format(elem, index+1)) # start counting from 1

Output:

dog = sheet.cell(r,1).value
cat = sheet.cell(r,2).value
pig = sheet.cell(r,3).value
cow = sheet.cell(r,4).value

Method 2: using a list comprehensions to construct a list of tuples

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))

Output:

dog = sheet.cell(r,1).value
cat = sheet.cell(r,2).value
pig = sheet.cell(r,3).value
cow = sheet.cell(r,4).value

关于python - 如何向列表的每个值添加一个字符串,然后将该字符串的值加起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com