2024-06-16 14:34:34 发布
网友
我试图将一个“i”计数器which is integer与一个包含str编号的列表进行比较,并将其添加到一个字符串变量中
LPL = ["1","2","3"] f = str() for i in range (x): if str(i) == LPL[i]: f+=str(i)
我希望f变量有比较的结果:f=123
请注意,您应该使用range从一个数字到一个数字,并且python索引从0开始,因此您需要以如下方式调整代码:
range
python
0
LPL = ["1","2","3"] f = str() for i in range (1, len(LPL)+1): ### note that your LPL[0] == 1 and not LPL[1] == 1, so you need to decreasee a number here, that's why a +1 in the range too if str(i) == LPL[i-1]: f+=str(i) ### OUTPUT >>> f '123'
也许我漏掉了一些东西,但是如果你想结合列表中的元素,或者通过连接字符串或添加整数,考虑使用Reult:
LPL = ["1","2","3"] LPL2 = [1,2,3] f = reduce(lambda a,b : a+b, LPL) # "123" f_int = reduce(lambda a,b : a+b, LPL) # 6
列表索引从0开始:
LPL = ["1","2","3"] s = "" for i in range(1,len(LPL)+1): if i == int(LPL[i-1]): s+=str(i) print(s)
请注意,您应该使用
range
从一个数字到一个数字,并且python
索引从0
开始,因此您需要以如下方式调整代码:也许我漏掉了一些东西,但是如果你想结合列表中的元素,或者通过连接字符串或添加整数,考虑使用Reult:
列表索引从
0
开始:相关问题 更多 >
编程相关推荐