【问题标题】:Append and Remove to check if the text is in the list追加和删除以检查文本是否在列表中
【发布时间】:2018-11-06 08:11:13
【问题描述】:

第 n 个评论被删除,第 n 个用户名在其他 cmets 中被检查,如果第 n 个用户名不在所有 cmets 中(第 n 个评论已被删除),它将被传递/附加到 warn_usernames 中,然后,第 n 个评论得到再次添加到 cmets 中。循环继续

usernames = ["a", "b", "c"]
warn_usernames = []
comments = [["b"], ["a", "c"], ["a", "b"]]

n = 0
while n < len(usernames):
    commente = comments[n]
    print(commente)
    usernamee = usernames[n]
    print(usernamee)
    comments.pop(n)
    if str(usernamee) not in str(comments):
       warn_usernames.append(usernamee)
    comments.insert(n, commente)
    n = n + 1
print(warn_usernames)

我得到的结果

[]

我希望得到的结果

[c]

提前致谢,我希望你能得到我的问题。

【问题讨论】:

  • 我不明白你的问题。部分问题是您反复写“cmets”,但它们似乎不是 Python cmets 或英文 cmets。请澄清什么是“评论”。
  • @RoryDaulton 评论只是一个列表
  • @RoryDaulton 完成
  • usernames 是字符串数组,但comments 是字符串数组,而不是字符串数组。因此if str(usernamee) not in str(comments) 行将不起作用。您需要遍历 comments 的数组。
  • 另外,我发现很难理解代码的目的。

标签: python python-3.x python-2.7 list append


【解决方案1】:

我认为你可以这样做:

usernames = ["a", "b", "c"]
warn_usernames = []
comments = [["b"], ["a", "c"], ["a", "b"]]
# use a loop for with enumerate on usernames to get a username and its index
for n, username in enumerate(usernames):
    #loop on all others comments than the nth
    for comments_to_check in comments[:n]+comments[n+1:]:
        #check the username is in comments_to_check and 
        if username not in comments_to_check:
            # append to warn_usernames if not
            warn_usernames.append(username)
            # stop the loop on comments to go to the next loop on usernames
            # to prevent multiple time the same username to be appened
            break 
print warn_usernames

你会得到预期的输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多