Python 以往数据对比

Python comparison of previous data

我有一个程序要求用户提供原始输入然后显示它。我想做的是:

如果用户输入的数据与之前输入的数据不同,则更新数据,否则什么都不做。

所以我所做的就是检查用户输入的数据是否与他们之前输入的数据相同,但我想知道如何在 Python.[=11 中执行此操作=]

这是一个简单的方法:

user_input = raw_input('enter an input\n')
user_input2 = raw_input('confirm your input\n')
if user_input != user_input2:
    print 'updating...'
    user_input = user_input2
print 'Input is: {}'.format(user_input)

如果您需要拆分输入字符串,请参阅 str.split 和其他方便的内置函数的文档: https://docs.python.org/2/library/stdtypes.html#str.split

执行此操作的自然方法是使用保证其元素唯一的数据结构。例如,尝试定义一个集合并向其中添加任何新的用户输入。如果您尝试添加集合中已有的字符串,它将不会执行任何操作。

record = set()
while True:  # just an example; you'll need to end the loop somehow
    message = raw_input('give me data! ')
    record.add(message)
print record