因此,作为"像计算机科学家一样思考"问题17.6的一部分,我写了一个名为袋鼠的课程:
class Kangaroo(object):
def __init__(self, pouch_contents = []):
self.pouch_contents = pouch_contents
def __str__(self):
'''
>>> kanga = Kangaroo()
>>> kanga.put_in_pouch('olfactory')
>>> kanga.put_in_pouch(7)
>>> kanga.put_in_pouch(8)
>>> kanga.put_in_pouch(9)
>>> print kanga
"In kanga's pouch there is: ['olfactory', 7, 8, 9]"
'''
return "In %s's pouch there is: %s" % (object.__str__(self), self.pouch_contents)
def put_in_pouch(self, other):
'''
>>> kanga = Kangaroo()
>>> kanga.put_in_pouch('olfactory')
>>> kanga.put_in_pouch(7)
>>> kanga.put_in_pouch(8)
>>> kanga.put_in_pouch(9)
>>> kanga.pouch_contents
['olfactory', 7, 8, 9]
'''
self.pouch_contents.append(other)
Run Code Online (Sandbox Code Playgroud)
让我疯狂的是,我希望能够编写一个字符串方法,通过__str__书面下面的单元测试.我现在得到的是:
In <__main__.Kangaroo object at …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个正则表达式,它将完整路径文件名转换为给定文件类型的短文件名,减去文件扩展名.
例如,我试图从字符串中获取.bar文件的名称
re.search('/(.*?)\.bar$', '/def_params/param_1M56/param/foo.bar')
Run Code Online (Sandbox Code Playgroud)
根据Python re docs,*?是不合适的版本*,所以我期待得到
'foo'
Run Code Online (Sandbox Code Playgroud)
返回,match.group(1)但我得到了
'def_params/param_1M56/param/foo'
Run Code Online (Sandbox Code Playgroud)
我在这里想到的贪婪是什么?
我有一个我正在为 SciKit Learn PCA 格式化的 DataFrame 看起来像这样:
datetime | mood | activities | notes
8/27/2017 | "good" | ["friends", "party", "gaming"] | NaN
8/28/2017 | "meh" | ["work", "friends", "good food"] | "Stuff stuff"
8/29/2017 | "bad" | ["work", "travel"] | "Fell off my bike"
Run Code Online (Sandbox Code Playgroud)
...等等
我想把它改成这个,我认为这对机器学习工作会更好:
datetime | mood | friends | party | gaming | work | good food | travel | notes
8/27/2017 | "good" | True | True | True | False | False | False …Run Code Online (Sandbox Code Playgroud) 我有一个代码,用于创建文件夹并在其中放置输出文件.我想使用try-except-else块和覆盖选项,可以设置为True或False,这样在文件夹已经存在并且overwrite设置为false的情况下,它将只打印文件夹已经存在,在所有其他情况下,它只会执行而不发表评论.
到目前为止,我提出的唯一解决方案如下:
def function( parameters, overwrite = False ):
try:
os.makedirs( dir )
except OSError:
if overwrite:
data making code...
else:
print dir + ' already exists, skipping...'
else:
if overwrite:
data making code...
Run Code Online (Sandbox Code Playgroud)
这个问题可能有更好或更优雅的解决方案吗?比如,例如,我不需要复制我的数据制作代码?这样做会让我想起太多的风格,我最终不得不用C语写一些东西,而且看起来并不像Pythonic.
python ×4
class-method ×1
coding-style ×1
dataframe ×1
greedy ×1
non-greedy ×1
pandas ×1
printing ×1
regex ×1
repeat ×1
scikit-learn ×1
string ×1
try-catch ×1