假设我定义了这个类:
class A:
pass
a = A()
Run Code Online (Sandbox Code Playgroud)
现在很明显我可以像这样设置属性:
a.x = 5
Run Code Online (Sandbox Code Playgroud)
但是setattr,我可以给出a名称中包含空格的属性.
setattr(a, 'white space', 1)
setattr(a, 'new\nline', None)
Run Code Online (Sandbox Code Playgroud)
dir(a)包含'white space'和'new\nline'.
我无法使用.运算符访问这些属性,因为它引发了SyntaxError:
>>> a.white space
File "<interactive input>", line 1
a.white space
^
SyntaxError: invalid syntax
>>> a.new\nline
File "<interactive input>", line 1
a.new\nline
^
SyntaxError: unexpected character after line continuation character
Run Code Online (Sandbox Code Playgroud)
但我可以getattr:
>>> getattr(a, 'white space')
1
>>> getattr(a, 'new\nline')
None
Run Code Online (Sandbox Code Playgroud)
这个功能背后有原因吗?如果是这样,它是什么?
我们应该使用它还是符合PEP8中定义的标准?
是否存在技术上的原因,为什么变量名称中不允许使用空格或者是否符合惯例?
例如,是什么阻止我们做这样的事情?:
average score = sum of scores / number of scores
Run Code Online (Sandbox Code Playgroud)
想到的唯一问题是关键字,但可以简单地限制它们在变量名中的使用,而词法分析器将能够区分变量的一部分和关键字.
variables programming-languages language-design variable-names
我有两个单独的词典,其中包含键和值,我想将它们相加.这些值应该只乘以它们所拥有的键.
即
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 15, 'b': 10, 'd': 17}
dict3 = dict.items() * dict.items()
print dict3
#### #dict3 should equal
{'a': 15, 'b': 20}
Run Code Online (Sandbox Code Playgroud)
如果有人可以提供帮助,那就太好了.谢谢!
是否可以将两个列表组合为键值对.两个列表中的元素数量相同.
我有两个列表如下.
list1 = ["a","b","c","d","e"]
list2 = ["1","2","3","4","5"]
Run Code Online (Sandbox Code Playgroud)
我如何组合如下
dict['a':1,'b':2,'c':3,'d':4,'e':5]
Run Code Online (Sandbox Code Playgroud) 在编写素数测试器时,我遇到了一个有趣的想法.当你想要做一些事情,如果一个操作的结果0,这是更好的('pythonic')解决它的方式?
# option A - comparison
if a % b == 0:
print('a is divisible by b')
# option B - is operator
if a % b is 0:
print('a is divisible by b')
# option C - boolean not
if not a % b:
print('a is divisible by b')
Run Code Online (Sandbox Code Playgroud)
PEP 8表示,与单身人士的比较None应与is运营商进行.它还说检查空序列应该使用not,而不是将布尔值与==或比较is.但是,它没有提到任何关于检查0结果的内容.
那么我应该使用哪个选项?
我很感激有人帮助解决这个问题:我在表格中有很多单词['word', 'another', 'word', 'and', 'yet', 'another'].我想将这些单词与我指定的列表进行比较,从而查找目标单词是否包含在第一个列表中.
我想输出哪些"搜索"单词包含在第一个列表中以及它们出现的次数.我尝试了类似的东西list(set(a).intersection(set(b)))- 但是它会分开单词并比较字母.
如何在一个单词列表中写入与现有的长列表进行比较?我怎样才能输出同时出现的频率?非常感谢你的时间和帮助.
我的问题是下面的代码为什么没有得到打印代替函数输出以及为什么函数输出在它的位置之前.
def print_spam():
print('spam')
def do_twice(r,ps):
g = ps()
print(r,'is a',g)
print(r,'is a',ps())
do_twice('xyz',print_spam)
Run Code Online (Sandbox Code Playgroud)
输出是
spam
xyz is a None
spam
xyz is a None
Run Code Online (Sandbox Code Playgroud) python ×6
attributes ×1
compare ×1
dictionary ×1
if-statement ×1
list ×1
variables ×1
words ×1