相关疑难解决方法(0)

空字符串布尔逻辑

我偶然发现了这个,我找不到足够的答案:

x = ""
Run Code Online (Sandbox Code Playgroud)

那么为什么是:

x == True
False

x == False
False

x != True
True

x != False
True
Run Code Online (Sandbox Code Playgroud)

我是否应该得出结论x既不是也不TrueFalse

python string boolean

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

评估类返回false

我写过这堂课:

class DSMCalc(object):
    def __init__(self, footprint):
        if footprint.__class__.__base__.__module__ is not 'shapely.geometry.base':
            raise TypeError('footprint input geometry is not a shapely geometry based object')
        self.footprint = footprint
Run Code Online (Sandbox Code Playgroud)

作为最好的,我可以告诉我需要做的全业务__class__.__base__.__module__,因为我想是包括所有匀称的对象(shapely.geometry.polygon.Polygonshapely.geometry.multipolygon.MultiPolygon,例如)和属性组合是我发现,好像这是可行的,因为所有的对象我想包括输出shapely.geometry.base.

但是,当我运行代码时,即使放入有效shapely.geometry.polygon.Polygon对象,我也会收到TypeError .我已经尝试了上面的代码shapely.geometry.base作为字符串和模块.怎么会这样?

一些示例对象重现错误:

valid_geojson_polygon_feature = {
'properties': {"name":"test"},
'type': 'Feature',
'geometry': {
    'coordinates': [[(-122.4103173469268, 37.78337247419125), (-122.41042064203376, 37.7833590750075),
                     (-122.41046641056752, 37.78360478527359), (-122.41047393562782, 37.783644775039576),
                     (-122.4103759761863, 37.78365638609612), (-122.4103173469268, 37.78337247419125)]],
    'type': 'Polygon'}}

from shapely.geometry import shape as get_shape
valid_shapely_polygon_feature = get_shape(valid_geojson_polygon_feature['geometry'])
print(valid_shapely_polygon_feature.__class__.__base__.__module__)
DSMCalc(valid_shapely_polygon_feature)
Run Code Online (Sandbox Code Playgroud)

python class shapely

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

在函数调用上强制默认重新评估

AFAIK,Python在声明时仅评估一次函数的默认值.所以调用以下函数printRandom

import random
def printRandom(randomNumber = random.randint(0, 10)):
    print randomNumber
Run Code Online (Sandbox Code Playgroud)

每次调用时都会打印相同的数字,不带参数.有没有办法randomNumber在不进行手动操作的情况下强制重新评估每个函数调用的默认值?以下是"手动"的含义:

import random
def printRandom(randomNumber):
    if not randomNumber:
         randomNumber = random.randint(0, 10)
    print randomNumber
Run Code Online (Sandbox Code Playgroud)

python

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

使用`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
查看次数

为什么列表的大小是其两倍?

给定列表:

x = [x for x in range(10)]
Run Code Online (Sandbox Code Playgroud)

打印出索引和值:

for i in range(-10, len(x)):
    print i, ": ", x[i]
Run Code Online (Sandbox Code Playgroud)

输出是:

-10 :  0
-9 :  1
-8 :  2
-7 :  3
-6 :  4
-5 :  5
-4 :  6
-3 :  7
-2 :  8
-1 :  9
0 :  0
1 :  1
2 :  2
3 :  3
4 :  4
5 :  5
6 :  6
7 :  7
8 :  8
9 :  9 …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

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

在python中传递可选的dataframe参数

我没有明确指定DataFrame下面代码中的列,而是试图给出一个传递数据框名称的选项,但没有太大的成功.

下面的代码给出了一个

"ValueError:维数错误"错误.

我尝试了另外几个想法,但它们都会导致一种或另一种形式的错误.

除了这个问题,当参数作为显式DataFrame列,p单个列和q列列表传递时,代码将按需运行.是否有一种聪明的(或实际上任何)传递数据框的方式,因此可以隐式地为列分配列?

def cdf(p, q=[], datafr=None):
    if datafr!=None:
        p = datafr[p]
        for i in range(len(q)):
            q[i]=datafr[q[i]]
...
(calculate conditional probability tables for p|q) 
Run Code Online (Sandbox Code Playgroud)

总结一下:

目前的用法:

cdf(df['var1'], [df['var2'], df['var3']])
Run Code Online (Sandbox Code Playgroud)

所需用法:

cdf('var1', ['var2', 'var3'], datafr=df)
Run Code Online (Sandbox Code Playgroud)

python dataframe pandas

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

如何比较模型字段和选择中的unicode字符串?Django的

我不确定哪个部分我做错了但不知何故我试图比较两个值,我100%确定它们匹配但不知何故代码不会执行.

假设我有这个模型(请原谅模型和字段名称有点拼写错误)

class TestOne(models):
    gender = models.Charfield(max_length=10, choices=GENDER_CHOICES)
Run Code Online (Sandbox Code Playgroud)

我的选择

GENDER_CHOICES = (("MALE", "MALE"), ("FEMALE", "FEMALE"))
Run Code Online (Sandbox Code Playgroud)

我很确定我的gender领域是MALE针对该对象所以我正在做这个声明,检查它是否MALE有所作为.

if a.gender is `MALE`:
    # do something here
Run Code Online (Sandbox Code Playgroud)

但它永远不会真实地达到它.我查a.gender了一个unicode类型,所以我甚str(a.gender)至做了确保它也是一个字符串,但仍然没有运气.

我在这里做错了吗?

PS我打印过a.gender并确保输出结果MALE

提前致谢

python django unicode if-statement compare

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

在python中为什么列表与list [:]不一样?

我有一个列表,ls = [0 1 2 3 4]我正在运行以下内容:

print(ls is ls[:])
Run Code Online (Sandbox Code Playgroud)

我得到的输出为False.为什么他们不是同一个名单?当我打印两个版本时,我会打印相同的列表.

python list

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

为什么'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
查看次数

Python3有助于确定动态创建列表的大多数pythonic方法

寻求专家的帮助,以帮助我在创建的程序中做出正确的选择.创建列表的两种方法中哪一种看起来更像Pythonic并且对您可读?或者,有没有更好的方法可以做到这一点?

方法#1 - 列表理解

def test_func(*args):
    s = 'Country name: United {nm}'
    l = [s.format(nm='States') if x is 'us' 
         else s.format(nm='Arab Emirates') if x is 'uae'
         else s.format(nm='Kingdom') if x is 'uk' 
         else 'Unknown' for x in args]
    return l

# execute
test_func('us', 'uk', 'uae')

# results
['Country name: United States',
 'Country name: United Kingdom',
 'Country name: United Arab Emirates']
Run Code Online (Sandbox Code Playgroud)

方法#2 - for循环

def test_func(*args):
    s = 'Country name: United {nm}'
    l = []
    for arg in args:
        if arg …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-3.x

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