这是比较一个整数的方法吗?我用它来检查它是否是一个字符串列表?

2024-04-19 22:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个“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


Tags: 字符串inwhich列表forifis计数器
3条回答

请注意,您应该使用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)

相关问题 更多 >