【问题标题】:Dictionary of father son names with options for user and outputs name of son, father, or grandfather带有用户选项的父子名称字典,并输出儿子、父亲或祖父的名字
【发布时间】:2013-11-21 23:01:09
【问题描述】:

我正在尝试将此文件制作成两个字典以通过用户的输入进行访问,但我完全迷失了。很遗憾,我已经为此工作了几个星期。我已经读取了文件,并且知道如何设置输入选项,而不是如何根据用户选项和名称来获取某个名称。

到目前为止,这是我的代码:

sonfather = {}
fatherson = {}
names = open('names.dat', 'r')
sonfather = names.read().split(',')

print sonfather

print "Father/Son Finder"
print "0 - Quit"
print "1 - Find a Father"
print "2 - Find a Grandfather"
print "3 - Find a Son"
print "4 - Find a Grandson"
print "5 - List of names"

control = ""
while control != "quit":
    choice = input("Enter your choice here: ")
    if choice == 0:
        control = "quit"
    elif choice == 1:
        print input("Enter the name of the son :")

【问题讨论】:

  • 仅仅通过这个就很难看出你想要完成什么。你能提供输入和预期输出吗?
  • 输入会说用户想找一个父亲。然后将提示他/她输入儿子的名字。使用儿子的名字,它将返回父亲的名字。当我运行儿子的打印时,我得到: ['john:fred', 'fred:bill', 'sam:tony', 'jim:william', 'william:mark', 'krager:holdyn', 'danny:布雷特,'丹尼:伊萨克','丹尼:杰克','布拉森:扎德','大卫:迪特','亚当:塞斯','塞思:诺斯']
  • 不是那个,文件输入。
  • 我对你在问什么感到有点困惑。
  • 我很困惑这个。哈哈

标签: python dictionary


【解决方案1】:
names = open('names.dat', 'r')
sonfather = names.read().split(',')
print sonfather

您必须了解对象的类型,才能正确使用与其相关的任何字典。因为除非它是字典类型,否则你不会得到字典类型的东西。

print 时的sonfather 是列表。它是一个包含字符串的列表。

您需要对该列表进行一些操作,这会将其“更改”为字典。仅仅因为它有"KEY:VALUE" 并不意味着它是一本字典。它是一个字符串。

对于初学者来说,您可能只想在冒号处拆分它们。

sonfather = [x.split(':') for x in sonfather]

[x for x in blabla] 这个东西是列表理解,它可能有点高级......但它和这个做同样的事情:

new_sonfather = []
for item in sonfather:
    new_sonfather.append(item.split(":"))
sonfather = new_sonfather

这将遍历sonfather 中的每个项目,用这种形式的列表替换它(高级pythonistas:我真的不知道...)"son:father" 变成['son','father']

那么你有一些看起来像这样的东西

sonfather = [['son1','father1'],['son2','father2'],['son3','father3'],['son4','father4']]

这几乎是您想要的位置。

然后这里变得超级神奇。

从这里把那个傻瓜转换成字典

son_father_dictionary = dict(sonfather)

aww 拍儿子。

在这一点上,son_father_dictionary 是词典俱乐部的真正官方卡片会员。

所以如果你要做一些疯狂的事情,比如:

print(son_father_dictionary['son1'])

输出将是father1

【讨论】:

  • 这很有意义。我已经卡在第一部分很长时间了。但是,那么如何从父亲的名字中输出祖父的名字呢?假设用户想从 ['son1'] 的输入名称中知道祖父的名字。
  • 您可以通过几种不同的方式做到这一点。最简单(但最难阅读)的方法就是以同样的方式制作另一本字典,可能称为father_grandfather_dictionary,然后转到print(father_grandfather_dictionary[son_father_dictionary['son1']])。如果您创建了一个具有“父亲”和“儿子”属性的对象,然后使用一些方法来确定谁是下一个血统(并添加儿子/父亲),那么您将拥有更好的运气和功能但是这条路线将涉及一个完整的重写你的整个代码。另外,您还需要学习如何处理类/对象...
  • 我尝试这样做的方式行不通。 son = raw_input("请输入儿子的名字:") if son in son_father_dictionary: the_father = son_father[son]
猜你喜欢
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多