i wrote python故事_你的python爸爸程序是谁

正如@kindall和@padrainchunningham在评论中所说,del_son是一个列表:del_son = raw_input("what father/son pair do you want to delete?(type first name of son").split(" ")

因为在这里你用空格隔开了它的名字。考虑到你的代码,我相信这是个错误,或者你在写这行代码时有些东西你不明白。在

在python中,不能使用list作为dict的键,因为dict需要它的所有键都是不可变的,以确保给定的键是唯一的。在python中,lists和dicts是可变的。这意味着当你这样做时:

^{pr2}$

i只是对以值1实例化的int对象的引用。当您将2分配给i时,值为1的前一个实例将被遗忘,并将由垃圾回收器收集。但当你这样做的时候:l = []

l.append(1)

l.append(2)

然后从l引用了一个list对象,修改后包含两个值:1和{}。现在,假设您想用dict中的list为一个值建立索引,然后:d = {}

l1 = [3,1]

l2 = [3,4]

d[l1] = 'foo'

d[l2] = 'bar'

天真地说,这没什么不起作用的:{[1,4]: 'foo', [3,4]: 'bar'}

但如果你这样做了呢:l1.remove(1)

l1.append(4)

那么dict怎么还能工作,因为dict会变成:{[3,4]: 'foo', [3,4]: 'bar'}

希望您得到了tuple类型,它是不可变和可散列的:d = {(3,1): 'foo', (3,4): 'bar}

所以你可能不想.split()它。您可能需要strip()它(这将删除所有前导和尾随的空白字符)。在

所以给你:del_son = raw_input("what father/son pair do you want to delete?(type first name of son").strip()

if del_son in fathers.keys():

del fathers[del_son]my two cents: to make it slightly more explicit, you'd better use del_son in fathers.keys(). It's actually the same as what you wrote, simply for readability it's easier, as del_son in fathers is misleading (which one could read as: "is the coder removing a son from the list of fathers? WTH?", whereas adding the .keys() will read "Ah! The coder is removing a father from a son→father mapping! Makes sense!")

高温

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值