好吧,我正试图在字典中提取前5个定义符,但我一直收到这个错误:
can only concatenate tuple (not "str") to tuple
在以下代码中:
def top():
datalist = sorted(Dictionary.dWord.items(), key=lambda x: x[1][0], reverse=True)
t = 1
tops, nums,dftop5 = [], [], []
for l in datalist:
if l[1] not in tops:
tops.append(l[1])
nums.append(str(l[1][1]))
if t == 5: # edit here
break
t+=1
for i, (top, num) in enumerate(zip(tops, nums)):
dftop5.append(top+": ("+num+" define(s)")
return dftop5
Dictionary.dWord.items()的设置如下:
{'testword': ('charles', 1, 'this is a test', 1389116045)}
Dictionary.dWord[word] = name, numdef, definition, wordtime
假设获得名称和numdef。
答案 0 :(得分:3)
您的排序键功能不正确:
datalist = sorted(Dictionary.dWord.items(), key=lambda x: x[2][0], reverse=True)
x
是对key, value
元组的引用,这意味着您需要通过x[1]
来访问该值:
datalist = sorted(Dictionary.dWord.items(), key=lambda x: x[1][0], reverse=True)
您的datalist
循环在尝试访问l[2][0]
而不是l[1][0]
时犯了同样的错误。