无法访问索引元组
我试图遍历一个字典,该字典本质上包含元组和元组的键,如下所示:
(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
我需要访问键的值,即元组的字符串。我尝试了很多事情,比如转换为字典,使用 key[0] 只是给我“'int'对象不可订阅”。
def matching_score(k, tokens, tf_idf_score):
print("Matching Score")
query_weights = {}
for word in tokens:
for key, value in tf_idf_score.items():
**if key in word**:
try:
query_weights[key[0]] += tf_idf_score[key]
except:
query_weights[key[0]] = tf_idf_score[key]
query_weights = sorted(query_weights.items(), key=lambda x: x[1], reverse=True)
print("")
l = []
for i in query_weights[:10]:
l.append(i[0])
print(l)
I'm trying to traverse through a dictionary that essentially contains tuples and keys for tuples like this:
(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
I need to access the value of the key, i.e., the string of the tuple. I tried many things, like converting to the dictionary, using key[0] just gives me "'int' object is not subscribable"..
def matching_score(k, tokens, tf_idf_score):
print("Matching Score")
query_weights = {}
for word in tokens:
for key, value in tf_idf_score.items():
**if key in word**:
try:
query_weights[key[0]] += tf_idf_score[key]
except:
query_weights[key[0]] = tf_idf_score[key]
query_weights = sorted(query_weights.items(), key=lambda x: x[1], reverse=True)
print("")
l = []
for i in query_weights[:10]:
l.append(i[0])
print(l)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,这是将数据重新创建为字典:
使用
keys()
可以访问键。同时,我们想将它们转换成一个列表。结果是一个元组列表。
[(101940039, 'yoel'), (101940039, 'yossi'), (101940039, 'youngmen')]
要访问此嵌套列表中的单个项目:首先,使用列表的索引选择所需的列表,然后使用元组的索引来选择其中所需的项目。
'yoel'
获取键元组的所有字符串元素:
yoel
yossi
youngmen
First, this is a recreation of your data as a dictionary:
With
keys()
it is possible to access the keys. At the same time, we want to convert them into a list.The result is a list of tuples.
[(101940039, 'yoel'), (101940039, 'yossi'), (101940039, 'youngmen')]
To access individual items in this nested list: first, use the index of the list to select the desired list, and second, use the index of the tuple to select the desired item within.
'yoel'
To get all the string elements of the key tuples:
yoel
yossi
youngmen