【问题标题】:How to print only when something gets added into a list?仅当将某些内容添加到列表中时如何打印?
【发布时间】:2018-11-20 21:57:44
【问题描述】:

我知道你有一个[1,2,3,4,5] 的列表等,我的想法是如果其中一些被弹出/删除,那么它不应该打印。比方说等我们删除号码3。在这种情况下,我们的列表将是[1,2,4,5],并且脚本应该是常用的。但是每当一个值被添加到列表中时。然后打印出整个列表等等。添加号码6 - > [1,2,4,5,6] - 打印出整个列表。

问题是我不想在删除任何内容时收到通知,所以我从一开始的想法是检查列表的长度,然后在更改时通知,但后来我意识到我错了我正在做的是它会在添加和/或删除时通知它,这就是我现在在这里的原因。

我所做的是比较 new_name_listold_name_list 但这一个将通知基本上会发生的任何变化。

import names


def get_value(value):

     value = names.get_full_name()

     names_list = []
     for names in names.get_last_name():
        names_list.append(names)
        break

     identifier = ('{} {}').format(value, names_list)

     return identifier


if __name__ == '__main__':

    old_name_list = get_value()

    while True:
        new_name_list = get_value()
        if new_name_list not in old_name_list:
            print("Yay new name added")

        else:
            print('I will re try again in 5 sec')
            time.sleep(5)

我的问题是 - 我怎样才能使它仅在 names_list 的值被通知时才打印

等等

1. [1,2,3,4,5] - print from beginning
2. [1,2,4,5] - Deleted 3 - Do not print
3. [1,2,4,5,6] - Print list, something got added
4. [1,4,5,6] - Deleted 2 - Do not print
5. .........

【问题讨论】:

    标签: python list printing add


    【解决方案1】:

    算法可能如下:

    1. 订购新旧列表。
    2. 如果长度相等 -> 逐个比较。如果新列表包含与旧列表不同的元素,则表示添加了新值。
    3. 如果新列表长度 > 旧列表长度,也意味着添加了新元素。

    例子:

    def detect_change(old_list, new_list):
        changed_flag = False
        old_list.sort()
        new_list.sort()
        if len(old_list) == len(new_list):
            for i in range(0, len(old_list)):
                if old_list[i] != new_list[i]:
                    changed_flag = True
        elif len(old_list) < len(new_list):
            changed_flag = True
        return changed_flag
    
    list1 = ["a", "b", "c", "d"]
    list2 = ["a", "b", "c", "k"]
    
    print(detect_change(list1, list2))
    

    【讨论】:

    • 嗯,好吧——我对你解释的算法一无所知。我明白了,但你介意做一个我可以更好地理解的编码示例吗?
    • 请检查更新后的答案 - 我已经为它添加了代码示例
    猜你喜欢
    • 2014-12-19
    • 2012-05-27
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多