故事是從這里開始的…
早上起床看到一條評論,有點懵逼,字典切片?
查閱了一下Python資料,3.6版本的Python改寫了dict的內部演算法,3.6版本之前是無序的;
So,現在就是有序的啦,注意的是這個順序是key的插入順序;
但字典雖有序沒下標怎么切片?list串列?
那就把key放進list里,利用list自身的截取方法切一下片!
再用截取后的key對新的字典賦值!
所以腦子一熱就寫了個字典切片1.0版本
# 字典切片1.0版本
def dictcut(dict, start, end):
# 臨時存放字典的key
temp = list(dict.keys())
# 回傳一個字典
result = {}
#切串列里的key
temp = temp[start:end]
for i in range(len(temp)):
#用切完后的key串列對新的字典賦值
result[temp[i]] = dict.get(temp[i])
return result
#原字典
dict = {"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4"}
print("dict:", dict)
start = eval(input("起始位置:"))
end = eval(input("結束位置:"))
#呼叫切片方法
newdict =dictcut(dict, start, end)
print("dictcut(dict,%d,%d):" % (start, end), newdict)
然后運行結果
-
兩個數為正,而且不越界,正常截取

-
如果我想從2截取到末尾,末尾坐標是-1,但傳[2 : -1]就會截取[2,-1),截取不到最后一個;那如果傳[2 : 0]就會像下面一樣
所以list[2: ]截取從2到最后一個,在傳參方面就顯得很麻煩了 -
如果截取[-5,-3]沒問題,但是[-3,-5]就不行了


綜上,我希望我的字典切片可以三百六四度無死角切,從正到負,從前到后,正著切,逆著切
所以字典切片2.0版本就登場了!
# 字典切片2.0
def dictcut(dict, start, end):
# 臨時存放字典的key
temp = list(dict.keys())
# 回傳一個字典
result = {}
# 分兩個分支 1.start和end在可切片范圍內 2.不在范圍內
if start <= len(temp) - 1 and start >= -len(temp) and end <= len(temp) - 1 and end >= -len(temp):
#start大于end,且下標不重疊
if start > end and start - 1 != len(temp) + end:
#start和end同時為大于等于0
if start >= 0 and end >= 0:
# (4,2) 4 0 1
for i in range(start, len(temp)):
result[temp[i]] = dict.get(temp[i])
for i in range(0, end):
result[temp[i]] = dict.get(temp[i])
# start和end同時小等于0
if start <= 0 and end <= 0:
# (-1,-3) 4 0 1
for i in range(len(temp) + start, len(temp)):
result[temp[i]] = dict.get(temp[i])
for i in range(0, len(temp) + end):
result[temp[i]] = dict.get(temp[i])
# start大于0,end小于0
if start >= 0 and end < 0:
# (1,-2) 1 2
for i in range(start, len(temp) + end):
result[temp[i]] = dict.get(temp[i])
# end大于start,且下標不重疊
elif end > start and start + len(temp) != end - 1:
# start和end同時為大于等于0
if start >= 0 and end >= 0:
# (0,3) 0 1 2
for i in range(start, end):
result[temp[i]] = dict.get(temp[i])
# start和end同時大小等于0
if start <= 0 and end <= 0:
# (-4,-1) 1 2 3
for i in range(len(temp) + start, len(temp) + end):
result[temp[i]] = dict.get(temp[i])
# end大等于0,start小于0
if end >= 0 and start < 0:
# (-1,3) 4 0 1 2
for i in range(len(temp) + start, len(temp)):
result[temp[i]] = dict.get(temp[i])
for i in range(end):
result[temp[i]] = dict.get(temp[i])
#start等于end,或者下標重疊
elif end == start or start + len(temp) == end - 1 or end <= 0 and start - 1 == len(temp) + end:
print("切了個寂寞!")
# start或者end不在范圍內
else:
print("傳入引數有誤!")
return result
#原字典
dict = {"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4"}
print("dict:", dict)
print("字典切割:左閉右開")
start = eval(input("起始位置:"))
end = eval(input("結束位置:"))
newdict = dictcut(dict, start, end)
# 如果回傳的字典不為空,列印結果
if len(newdict) != 0:
print("dictcut(dict,%d,%d):" % (start, end), newdict)
運行結果:
-
若不在范圍

-
如果坐標重疊,重疊切個寂寞哦?

-
360°無死角切切切(正常切)
正數
負數
-
360°無死角切切切(從后往前切)
正數
負數
2.0代碼比較繁瑣,但是字典切片的效果還是清晰可見的~~~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/195295.html
標籤:其他
