相关疑难解决方法(0)

关键字:is和=在python中有什么区别

根据python样式指南,python关键字is应该用于代替==运算符.

然而,它们并不总是与此处所示完全相同.为什么?实际差异是什么,适当的用法是什么?

import unittest

class testIS(unittest.TestCase):
    def test_is(self):
        self.assertEqual(1,1)

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

哪个有效...但以下不...

import unittest

class testIS(unittest.TestCase):
    def test_is(self):
        self.assertEqual(1,1)

if __name__ is '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

python syntax keyword

3
推荐指数
2
解决办法
343
查看次数

在Python中,单个字符串是否保证相同?

我读到了某个地方(我想,也可能是其他地方的SO帖子),Python自动引用单个字符串,所以不仅如此'a' == 'a',而且'a' is 'a'.

但是,我不记得读取这是否是Python中的保证行为,还是只是特定于实现?

官方来源的奖励积分.

python string identity

2
推荐指数
2
解决办法
205
查看次数

有没有时候`is`运算符可以在Python中用两个相似的字符串返回false?

我有一些代码,我是编辑,使其一目了然更容易理解,我想我应该改变所有的char=="|"char is "|".我知道看起来我太过分了,但看起来确实好看了.无论如何,我pycheck最后一次决定,我得到了这个警告:

Warnings...

test.py:7: Using is |, may not always work
Processing module test (test.py)...
Run Code Online (Sandbox Code Playgroud)

对于我的生活,我无法想象除非你开始冒险进行多字节字符编码,CJK字符等,如果我没有错,那么它"|" is "|"将会返回False.还有其他一些我错过的情况吗?

python string comparison

2
推荐指数
2
解决办法
245
查看次数

将if-elseif语句转换为字典

我有以下代码用于对服务器进行RESTful调用:

def request(self, request, account_id, user):

    if request is 'get_id':
        #Get user from id
        result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)

    elif request is 'get_username':
        #Get user from username
        result = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)

    elif request is 'get_email':
        #Get user from username
        result = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)

    elif request is 'post':
        #Add user to new account
        result = requests.post(api_root + '/accounts/' …
Run Code Online (Sandbox Code Playgroud)

python dictionary design-patterns switch-statement

2
推荐指数
1
解决办法
221
查看次数

检查变量是否是python中的字典 - 使用'is'或==

简介:我有一个名为'parent'python中的字典的变量.我想检查它是否是一个dict对象.但是,使用"type(parent) is dict"给了我'False'.

注意:我的python脚本中加载了以下库:

from google.appengine.ext import ndb
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我首先怀疑是因为这个变量'parent'是使用json库的'loads'方法创建的.

parent = json.loads(self.request.body)
Run Code Online (Sandbox Code Playgroud)

但是,即使我这样创建父母,

parent = {}
Run Code Online (Sandbox Code Playgroud)

我得到与下面观察到的相同的结果:

        print type(parent)
          >> <type 'dict'>
        print type(parent) is dict
          >> False
        print type({}) is type(parent)
          >> True
        print type(parent) == dict
          >> False
        print type({}) == type(parent)
          >> True
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?这是python版本问题吗?或者这与我加载谷歌的应用引擎库的事实有关吗?当我在普通终端中执行以下命令时,没有加载库(Python 2.7.5),我得到以下结果,这是我所期望的:

Python 2.7.5 (default, Sep 12 2013, 21:33:34) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
>>> parent …
Run Code Online (Sandbox Code Playgroud)

python google-app-engine json

2
推荐指数
1
解决办法
4323
查看次数

为什么字符串相等不能按预期在这个Python代码中工作?

注意:在你走之前和downvote或关闭我的问题,或将其标记为重复的,让我向你保证,我已经看了几十个几十对SO和GOOGLE了类似的问题,但后一个多小时,我还没有得到解决这个问题.没有其他答案解决了我的问题.

问题 我有这个Python代码:

text = ''
text += '<' + '/' + '>'

print text, '</>'
print repr(text), repr('</>')

if text is '</>':
    print 'Equal'
else:
    print 'Not equal!'
Run Code Online (Sandbox Code Playgroud)

我只是想比较两个字符串.出于某种原因,我需要text逐个连接字符.我期望if-statement要评估,True但事实并非如此.我不知道为什么!

这是输出:

</> </> '</>' '</>' Not equal!

我是Python的新手,我使用的是Python 2.7.请帮忙吗?

python

2
推荐指数
1
解决办法
6577
查看次数

使用`is`检查空字符串

is在Python中检查空字符串是否正确?它进行身份检查,同时==测试相等性.

考虑以下(使用的想法join是从这个答案借来的):

>>> ne1 = "aaa"
>>> ne2 = "".join('a' for _ in range(3))
>>> ne1 == ne2
True
>>> ne1 is ne2
False
>>>
Run Code Online (Sandbox Code Playgroud)

所以这里的is工作可以预期.现在来看看这段代码:

>>> e1 = ""
>>> e2 = "aaa".replace("a", "")
>>> e3 = "" * 2
>>> e4 = "bbb".join(range(0))
>>> e1, e2, e3, e4
('', '', '', '')
>>> e1 is e2
True
>>> e1 is e3
True
>>> e1 is e4
True
>>> id(e1), …
Run Code Online (Sandbox Code Playgroud)

python identity equals

1
推荐指数
2
解决办法
1399
查看次数

为什么'a'+'bc'导致与'abc'不同的字符串(非is)?

我试图弄清楚为什么后面的“ x”和“ y”不同。

>>> x = 'a' 
>>> x += 'bc'
>>> x
'abc'
>>> y = 'abc'
>>> x is y
False
>>>

>>> id(x)
4537718624
>>> id(y)
4537059288
>>>
Run Code Online (Sandbox Code Playgroud)

为什么ID不同?我不是在寻找有关“ is”运算符的信息。我试图弄清楚为什么串联后创建的新对象不同于'y'。

python string

1
推荐指数
1
解决办法
703
查看次数

为什么'list is list(list)'在python中是假的?

num = [1,2,3,4]
num == list(num) 
Run Code Online (Sandbox Code Playgroud)

它给出True,其中,

num is list(num)
Run Code Online (Sandbox Code Playgroud)

给出False

这两者有什么区别?python在这两个语句中做了什么?

python identity list python-3.x

1
推荐指数
1
解决办法
1408
查看次数

为什么这个条件lambda函数没有返回预期的结果?

我仍然在使用python和pandas.我正在努力改进关键字评估.我的DF看起来像这样

Name  Description 
Dog   Dogs are in the house
Cat   Cats are in the shed
Cat   Categories of cats are concatenated

I am using a keyword list like this ['house', 'shed', 'in']
Run Code Online (Sandbox Code Playgroud)

我的lambda函数看起来像这样

keyword_agg = lambda x: ' ,'.join x if x is not 'skip me' else None
Run Code Online (Sandbox Code Playgroud)

我正在使用一个函数来识别和评分每一行的关键字匹配

def foo (df, words):
    col_list = []
    key_list= []
    for w in words:
        pattern = w
        df[w] = np.where(df.Description.str.contains(pattern), 1, 0)
        df[w +'keyword'] = np.where(df.Description.str.contains(pattern), w, 
                          'skip me')
        col_list.append(w)
        key_list.append(w + …
Run Code Online (Sandbox Code Playgroud)

python lambda conditional pandas

0
推荐指数
1
解决办法
51
查看次数

如果不是myList和myList是否在[]中是什么区别?

当我遇到一个小问题时,我正在处理一些代码.我有点像这样:

if myList is []:
    # do things if list is empty
else:
    # do other things if list is not empty
Run Code Online (Sandbox Code Playgroud)

当我运行程序(并且让myList为空)时,程序将直接进入else语句,这让我感到惊讶.但是,在查看此问题后,我将代码更改为:

if not myList:
    # do things if list is empty
else:
    # do other things if list is not empty
Run Code Online (Sandbox Code Playgroud)

这使得我的程序按照我的预期工作(它运行'if not myList'部分而不是'else'语句).

我的问题是这个if语句的逻辑发生了什么变化?我的调试器(我使用Pycharm)说myList两次都是空列表.

python if-statement list empty-list

0
推荐指数
1
解决办法
185
查看次数

如果字符串是特定的字符串,请将其设为int?

我有一个字符串列表,并希望循环遍历列表,如果它是一个特定的字符串,则使列表中的值为0.下面是我正在尝试的代码,但它不起作用:

variable1 = ['None', 'One', 'Two', 'Three', 'None']   
variable2 = [0 if v is 'None' else v for v in variable1]
Run Code Online (Sandbox Code Playgroud)

结果应该是:[0,'One','Two','Three',0]但它不会改变None字符串.

python list-comprehension list python-3.x

0
推荐指数
1
解决办法
40
查看次数