循环浏览一个列表以查看是否有任何用户名对应于其他列表

2024-04-25 15:09:10 发布

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

所以,如果一个名为new\u users的列表要循环通过,并检查是否有任何名称对应于另一个名为current\u user的列表,那么如何执行此任务呢?另外,将这些新用户附加到当前列表中。你知道吗

import time, sys
c_users = ['admin', 'eric', 'eon', 'joseph', 'anton', 'oscar', 'pontus']
n_users = ['joseph', 'eon', 'yasmina', 'jeremiah', 'mugabe']
actually_new_users = list(set(n_users) - set(c_users))
c_users = list(set(c_users).union(set(n_users)))

if not c_users:
      print("List is empty")

for user in c_users:
        print ("Hello, " + c_users [0]+"." + " Do you want a status report?")
        statusr=str(input("Y/N: "))
        if  statusr == "Y" or "y":
            print("The status report is being drafted")
            time.sleep(0.5)
            sys.stdout.write(".")
            time.sleep(1)
            sys.stdout.write(".")
            time.sleep(1)
            sys.stdout.write(".")
            time.sleep(2)
            sys.stdout.flush()
            sys.stdout.flush()
            sys.stdout.flush()
            print("\n")

        elif statusr == "N" or "n":
            print("No status report today, OK.")
        else:
            print("error")
        time.sleep(10)
        print(actually_new_users)
        ##print ("Hello, " + str(c_users))
        ##time.sleep(0.5)
        ##print ("Hello, " + c_users [2])
        ##time.sleep(0.5)
        ##print ("Hello, " + c_users [3])
        ##time.sleep(0.5)
        ##print ("Hello, " + c_users [4])
        break

Tags: reporthello列表newtimestatusstdoutsys
1条回答
网友
1楼 · 发布于 2024-04-25 15:09:10

正如有人在评论中指出的,列表不是存储这些信息的最合适的数据结构。当您想确保一个集合的成员不存在于另一个集合中时,应该使用set来强制执行此操作。你知道吗

如果你坚持要有清单,那么最简单的方法就是

current_users = ["bob", "sally"]
new_users = ["harry",  "sally"]
current_users = list(set(current_users).union(set(new_users)))
print(current_users)

>>> ['bob', 'sally', 'harry']

这里使用.union()来更新current_users中的new_users新用户。如果您想知道new_users中的哪些用户已经在current_users中,那么您可以这样使用.intersection()

actually_new_users = list(set(new_users) - set(current_users))
print(actually_new_users)

>>> ['harry']

这有点低效,因为它会导致大量的复制,但它仍然可能比两个列表之间的O(n^2)比较好。你知道吗

*取决于列表的大小。你知道吗

相关问题 更多 >