遍历一个列表以查看是否有任何用户名对应于另一个列表Python

时间:2018-08-14 14:40:28

标签: python list loops

因此,如果要遍历一个名为new_users的列表,并检查是否有任何名称与另一个名为current_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

1 个答案:

答案 0 :(得分:3)

正如某人在评论中指出的那样,列表不是存储此信息的最合适的数据结构。当您要确保一个集合的成员不在另一个集合中时,应使用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)比较好。

*取决于列表的大小。