如何在循环中删除一个列表中的元素?

我正在运行一个循环来检查我的 “新用户 “是否已经在 “当前用户 “列表中。如果没有,他们就会被添加到当前用户列表中,然后从新用户列表中删除。

在检查发生后,我似乎很难删除新用户列表中的元素。当我在第32或33行添加行时,我没有得到预期的结果。

我的代码如下。

# Task at hand: Checking Usernames
# create a program that simulates
# how websites ensure that everyone has a unique username.


# HELP NEEDED - Current issue:
# Can't seem to be able to remove the new user once he has been added to the 
# current_user list. 


current_users = ['paul', 'bob', 'robert', 'maria', 'admin']
new_users = ['vali', 'donal', 'aoife', 'robert' , 'gerry']

if current_users:
    if new_users:

        for new_user in new_users:
            if new_user.lower() in current_users:
                print(f'This user already exists. Please chose a new user:  {new_user.title()}')

            else:

            # I also tried replacing "else:" with "if new_user.lower() not 
            # in current_users:" but no luck.

                current_users.append(new_user.lower())
                print(f"Perfect, you have been added to the database: {new_user.title()}")

                # I could not manage to remove the new_user from the list
                # straight from here. 
                # I tried the following 2 'solutions':
                # del new_users[0]
                # new_users.remove(new_user.lower())

    else:
        print("You need new users to check against.")

else:
    print("You need some existing users to check against.")


# Check status of lists: 
print(f"\nCurrent users: {current_users}")
print(f"New users: {new_users}")

解决方案:

复制一个 new_users 来迭代,然后从原始列表中删除。

current_users = ['paul', 'bob', 'robert', 'maria', 'admin']
new_users = ['vali', 'donal', 'aoife', 'robert' , 'gerry']

if current_users:
    if new_users:
        for new_user in new_users.copy():
            if new_user.lower() in current_users:
                print(f'This user already exists. Please chose a new user:  {new_user.title()}')
            else:
                current_users.append(new_user.lower())
                print(f"Perfect, you have been added to the database: {new_user.title()}")
                new_users.remove(new_user)
    else:
        print("You need new users to check against.")
else:
    print("You need some existing users to check against.")

# Check status of lists:
print(f"\nCurrent users: {current_users}")
print(f"New users: {new_users}")

这就避免了修改你正在迭代的列表的问题。

输出。

Current users: ['paul', 'bob', 'robert', 'maria', 'admin', 'vali', 'donal', 'aoife', 'gerry']
New users: ['robert']

给TA打赏
共{{data.count}}人
人已打赏
未分类

我如何将一个变量从刀片文件传递到 laravel 中的控制器?

2022-9-8 21:16:39

未分类

如何通过浏览器扩展的javascript代码上传json到S3?

2022-9-8 21:16:41

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索