列表中增加整数元素的问题

Consider the list: mylist = [1,2,3,'a','b',4,5,'c',6]

What I want to do is make a program that returns the list after incrementing each integer element by 1, skipping through the non-integer elements. I tried the following code to define a function using the while loop with parameter x:

def f(x):
    i = -1
    while (i < (len(x) - 1)):
        i+=1
        if (type(x[i]) != "<class 'int'>"):
            continue
        x[i]+=1
    return x

Now, I try to use this function to return the value of f(mylist). Following is the output:

[1, 2, 3, 'a', 'b', 4, 5, 'c', 6]

如您所见,它返回输入本身,当我实际希望将其输入时,这是非常意外的

[2, 3, 4, 'a', 'b', 5, 6, 'c', 7]

即使多次查看我的代码,我也找不到它出了什么问题。

如果有人为我解决这个问题会很高兴。

评论
  • 囚心锁
    囚心锁 回复

    你可以做

    def f(x):
        return [i + 1 if type(i) == int else i for i in x]
    

    或通过for循环

    def f(x):
        for i, v in enumerate(x):
            if type(v) == int:
                x[i] += 1
        return x
    

    此函数将返回一个新列表,该列表将每个int值增加一个,对于其他值,它将保持原样。 该函数将返回

    [2, 3, 4, 'a', 'b', 5, 6, 'c', 7]