我有一本字典,我想迭代键,测试键,然后打印通过测试的键.
例如,我的代码目前看起来像这样:
x = {4:"a", 1:"b", 0:"c", 9:"d"}
for t in x:
if t > 2:
print t
Run Code Online (Sandbox Code Playgroud)
然而,所有的输出,只是关键.
如何让代码打印出代码末尾的值而不是密钥?
另外,我如何以字典的形式获得这个{key : value}
?
你可以试试这个: print t, x[t]
或这个:
for key, val in x.items():
if key > 2:
print key, val
Run Code Online (Sandbox Code Playgroud)
如果您只想获得要打印到新词典中的对,那么您必须将它们放在那里:
newdict = {}
for key, val in x.items():
if key > 2:
print key, val
# put all the keys > 2 into the new dict
newdict[key] = val
Run Code Online (Sandbox Code Playgroud)
当然,该解决方案是在插入时进行打印.如果你做的不仅仅是一个小脚本,那么你可以通过破坏功能获得更多的功能,确保任何给定的功能只做一个,而且只做一个:
def filter_dict(x):
newdict = {}
for key, val in x.items():
if key > 2:
# put all the keys > 2 into the new dict
newdict[key] = val
def pretty_print(dct):
for k, v in dct.items():
print k, v
filtered = filter_dict(x)
pretty_print(dct)
Run Code Online (Sandbox Code Playgroud)
当然,如果您只是调试,这不适用,并且有些方法取决于您正在编写的程序的大小:如果您做的很简单,那么您可以获得额外的灵活性由于额外努力确定任何给定事物的确切内容,因此打破功能失去了.那说:你一般应该这样做.
另外,在Python中简单比较过滤列表的最惯用方法是使用dict理解(Python 2.7/3.0中的新增功能):
filtered = {key: val for key, val in x if key > 2}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1060 次 |
最近记录: |