我试图在对列表进行更改后删除列表中的某个项目,但它不会删除,我不明白为什么

2024-04-23 22:01:06 发布

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

我的代码的目的是获取用户的输入,并检查每个字符是字符串还是整数。然后它会将角色放入不同的列表中

如果你知道更好的方法,请说。这是我唯一能想到的

user_inp = input("please give me an input")


def split_func():
    for i in user_inp:
        user_inp_split.append(i)

def check():

    for i in user_inp:
        try :
            temp = int(i)
            items2.append(temp)
            del user_inp_split[i]
            # the line that wont work 


            print (user_inp)

            print (user_inp_split)

        except:
            print ("get to stage 2")

Tags: 字符串代码用户in目的forinputdef
1条回答
网友
1楼 · 发布于 2024-04-23 22:01:06

欢迎来到StackOverflow,您遇到的问题是您没有一个有组织的代码,我重新组织了您的代码,以便完成您想要的任务:

user_inp = input("please give me an input: ")
user_inp_split = list(user_inp) #user input converted to list
items2 = [] #Character list
items1 = [] #integer list

def check():
    for i in user_inp_split: #iterates over the user_input list
        try :
            items1.append(int(i,10)) #Convert the items to an integer with base on 10
        except ValueError:
            items2.append(i) #if not, append to the items2 list
    print ("User input {}".format(user_inp))
    print ("Characters {}".format(items2))
    print ("Integers {}".format(items1))
check() #call the function, otherwise it wont work

首先,您必须声明要附加到的列表(第3行和第4行),然后我们必须迭代,并检查它们是否为整数,如果它们可以用内置函数^{}转换,则它们为整数,否则它们不是(第8行到第11行),最后我们打印用户输入以检查一切是否正常

相关问题 更多 >