我有字典复制方法的问题例如让我说我有
>> d = {'pears': 200, 'apples': 400, 'oranges': 500, 'bananas': 300}
>> copy_dict = d.copy()
Run Code Online (Sandbox Code Playgroud)
现在,如果我检查d和copy_dict的id,则两者都不同
>> id(d)
o/p = 140634603873176
>> id(copy_dict)
o/p = 140634603821328
Run Code Online (Sandbox Code Playgroud)
但如果我检查字典中对象的id,它们是相同的意思是id(d ['pears'])= id(copy_dict ['pears'])
>> id(d['pears'])
o/p = 140634603971648
>> id (copy_dict['pears'])
o/p = 140634603971648
Run Code Online (Sandbox Code Playgroud)
新dict中的所有对象都引用与原始dict相同的对象.
现在,如果我在d中更改键'pears'的值,copy_dict中的相同键没有变化,当我现在检查id时,id(d ['pears'])!= id(copy_dict ['pears'] )
>> d['pears'] = 700
>> print copy_dict['pears']
o/p = 200
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果新dict中的对象是与原始字典相同的对象的引用,为什么当原始字典中的值发生更改时,新字典的值不会改变,以及Python如何立即更改id因为它看到价值变了?
你能否详细说明深浅拷贝的区别?
鉴于以下代码:
a = '1'
if a == 1:
print 'yes'
else:
print 'no'
Run Code Online (Sandbox Code Playgroud)
我们得到输出为no。
Python 如何将字符串值与这里的 int 值进行比较 ( if a == 1)?在 C 中,这样的比较会产生错误,因为这是在比较不同的类型。
你能解释一下如何在python中运行吗?我知道什么时候
x y and
0 0 0 (returns x)
0 1 0 (x)
1 0 0 (y)
1 1 1 (y)
Run Code Online (Sandbox Code Playgroud)
在翻译中
>> lis = [1,2,3,4]
>> 1 and 5 in lis
Run Code Online (Sandbox Code Playgroud)
输出给出FALSE
但,
>>> 6 and 1 in lis
Run Code Online (Sandbox Code Playgroud)
输出为TRUE
它是如何工作的?
在这种情况下该怎么做在我的程序中我必须输入if条件只有当两个值都在列表中时?
我想知道rstrip和lstrip在python中是如何工作的.说,如果我有一个字符串
>> a = 'thisthat'
>> a.rstrip('hat')
out : 'this'
>> a.lstrip('this')
out: 'at'
>> a.rstrip('cat')
out: 'thisth'
Run Code Online (Sandbox Code Playgroud)
如何剥离一个单词?
理想情况下,输出应该是"thist"(对于第一种情况)和"那种"(对于第二种情况)对吗?
或者它是否像正则表达式一样,匹配每个字符,以及它最终剥离的哪个字符(第三种情况)?
注意:我不是在寻找替换我只是想知道从字符串中剥离子字符串时strip是如何工作的.