0

我是 Python 新手,正在尝试创建一个非常简化的foursquare 版本。

我希望用户能够签到以及按日期和位置搜索他们以前的签到。我拥有的代码似乎可以在签入时正常工作,但搜索并未将结果返回给用户。我知道我在for循环中的措辞不正确,但我对如何搜索字典感到困惑。

非常感谢您的帮助。

print("What would you like to do? \n1 Check-in \n" \
  "2 Search check-ins by date \n3 Search check-ins by location \n4 Exit")

while True:
    import datetime
    current_date = str(datetime.datetime.now())
    check_in = {}
    choice = input("\nYour choice: ")

    if choice == '1':
        location = input("\nPlease enter your current location: ")
        check_in[current_date] = location
        print("You have checked in at", location, current_date)

    elif choice == '2':
        date_search = input("Please enter a date (yyyy/mm/dd) ")
        for date in check_in.keys():
            if date_search in check_in(date):
                print(check_in[key])

    elif choice == '3':
        location_search = input("Please enter a location: ")
        for date in check_in.keys():
            if location_search in check_in(date):
                print(date)

    elif choice == '4':
        break
4

2 回答 2

1

几点说明:

  1. 每次通过循环,你都在冲洗check_in. 不管我们之前在里面放了什么,当我们回到它时它就不会存在了。

  2. 选择 2 可以简化为一个简单的d.get(key)陈述。你可以在这里查看它是如何工作

  3. 您使用的密钥不会按照您认为的方式打印。如果我输入一个位置,比如“家”,则键显示为:

    Please enter your current location: Home
    You have checked in at Home 2012-04-16 19:44:26.235305
    {'2012-04-16 19:44:26.235305': 'Home'} # Print statement added by me.
    

注意到所有这些额外的信息了吗?是的,不是你所期望的。如果您只想获取日期部分,您可以更多datetime地查看模块以了解如何使其完美,或者偷懒(就像我在调试时一样),并使用datetime.datetime.now().split()[0]. 这段令人费解的代码将字符串按空格拆分,然后获取第一个元素 - 或'2012-04-16'

最后一个选择我将作为练习留给你,但我认为检查字典文档足以让你开始。

于 2012-04-17T01:47:56.590 回答
0

将您的 s 更改inputraw_inputs,否则在 Python 2.7.2 中,此代码将评估inputas 代码,而不是实际的数字或字符串。不完全是你想要的,我想。

至于您在字典中搜索的最后一个问题,您在字典中的匹配检查将永远不会匹配。您在 while 的check_in每个循环上重新初始化变量。您还将当前日期/时间以不同于您接受用户输入的格式输入到字典中。

请输入您当前的位置:首页

('你已经在', '家', '2012-04-16 20:43:08.891334')

您的选择:2

请输入日期 (yyyy/mm/dd) 2012/04/16

你的选择:

您需要规范化您的数据和输入,并移出check_inwhile 循环。

    print("What would you like to do? \n1 Check-in \n2 Search check-ins by date \n3 Search check-ins by location \n4 Exit")


check_in = {}

while(True):
    import datetime
    current_date = datetime.datetime.now().strftime("%Y/%m/%d")
    choice = raw_input("\nYour choice: ")

    if(choice == '1'):
        location = raw_input("\nPlease enter your current location: ")
        check_in[current_date] = location
        print check_in

    elif(choice == '2'):
        date_search = raw_input("Please enter a date (yyyy/mm/dd) ")
        for date,location in check_in.iteritems():
            if date_search == date:
                print "%s - %s" % (date,location)

    elif(choice == '3'):
        location_search = raw_input("Please enter a location: ")
        for date,location in check_in.iteritems():
            if location_search == location:
                print "%s - %s" % (date,location)
    elif(choice == '4'):
        break
于 2012-04-17T01:51:50.687 回答