Last active
October 20, 2022 18:10
-
-
Save ayuLiao/d19a0ac3ff2a5de05e38e6737eba6ca1 to your computer and use it in GitHub Desktop.
在python中字典是无法使用切片的,自定义一个方法,用于实现字典切片
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#先取出所有 keys,再对 keys 切片,然后用得到的键去字典里找值重新创建一个新的字典 | |
def dict_slice(adict, start, end): | |
keys = adict.keys() | |
dict_slice = {} | |
for k in keys[start:end]: | |
dict_slice[k] = adict[k] | |
return dict_slice | |
#更优雅的版本 | |
dict_slice = lambda adict, start, end: dict((k, adict[k]) for k in adict.keys()[start:end]) | |
#如果是 python 2.7 及以上的版本,还可以用 dict comprehension 来替换 dict() 函数 | |
dict_slice = lambda adict, start, end: { k:adict[k] for k in adict.keys()[start:end] } | |
``` | |
使用一下 | |
``` | |
In [17]: d = {}.fromkeys(range(10), 5) | |
In [18]: d | |
Out[18]: {0: 5, 1: 5, 2: 5, 3: 5, 4: 5, 5: 5, 6: 5, 7: 5, 8: 5, 9: 5} | |
In [19]: slice = dict_slice(d, 3, 5) | |
In [20]: type(slice) | |
Out[20]: dict | |
In [21]: slice | |
Out[21]: {3: 5, 4: 5} |
新手,输入后弹出'dict_keys' object is not subscriptable
def dict_slice(adict, start, end):
keys = adict.keys()
dict_slice = {}
for k in list(keys)[start:end]: #list(keys)
dict_slice[k] = adict[k]
return dict_slice
dict_slice = lambda adict, start, end: dict((k, adict[k]) for k in list(adict.keys())[start:end])
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
新手,输入后弹出'dict_keys' object is not subscriptable