[英]Finding maximum and minimum of list of lists using dictionary
我试图在列表列表中找到最大值和最小值。 详细地说,我有这个存储推文的变量:
lines = [['ladybug7501',
'RT SamaritansPurse: You can help the many across #PuertoRico who remain in desperate need after #HurricaneMaria. See how here: …',
'Negative',
-1],
['DyEliana',
'RT daddy_yankee: La madre naturaleza está azotando con potencia a sus hijos. Mi corazón y mis oraciones con mi tierra #PuertoRico y mis he…',
'Neutral',
0],
['waffloesH',
'RT SteveCase: PLEASE HELP: ChefJoseAndres is working tirelessly to feed #PuertoRico, but urgently needs our help: ',
'Neutral',
0],
['SteveLevinePR',
'RT StarrMSS: .elvisduran gave 30K to @Bethenny to charter plane to bring supplies to #PuertoRico HurricaneMaria. He also gave 100K to ',
'Neutral',
0],
['bronxdems',
'RT theCEI: THANK YOU to rubendiazjr and the NY Hispanic Clergy for organizing an amazing event last week in support of PuertoRico! 🇵🇷❤️…',
'Positive',
3]]
它有更多列表,但我只发布了一个示例。 我已经完成了大部分繁重的工作来达到这一点。 我想要做的是打印出具有最高积极词和最高消极词的推文。 列表最后一个切片上的数字越高,它就越积极。 (-1、0 和 3)。 我正在尝试打印出与之相关的最高价值的推文。
这是我一直在玩的一些代码:
user_lines = []
for line in lines:
freqs = {}
user_lines.append(line[2])
for i in user_lines:
if i not in freqs:
freqs[i] = 1
else:
freqs[i] += 1
freqs
但这就是我所拥有的。 有人有想法么?
您可以通过指定max
和min
的键来尝试
mini=min(lines, key=lambda x: x[-1])
maxi=max(lines, key=lambda x: x[-1])
print(mini)
print(maxi)
Output:
mini
['ladybug7501', 'RT SamaritansPurse: You can help the many across #PuertoRico who remain in desperate need after #HurricaneMaria. See how here: …', 'Negative', -1]
maxi
['bronxdems', 'RT theCEI: THANK YOU to rubendiazjr and the NY Hispanic Clergy for organizing an amazing event last week in support of PuertoRico! 🇵🇷❤️…', 'Positive', 3]
如果您只想在字典中保存最差和评分最高的推文,您可以iterate
推文并保存放置最差/最佳评分的索引。 之后,您可以将这些索引的信息保存到这样的字典中:
highest = 0
lowest = 0
dic = {}
for i, line in enumerate(lines):
number_of_likes = line[3]
if number_of_likes < lowest:
lowest = i
if number_of_likes > highest:
highest = i
dic['lowest'] = [lines[lowest][3], lines[lowest][1]]
dic['highest'] = [lines[highest][3], lines[highest][1]]
output:
{'lowest': [-1, 'RT SamaritansPurse: You can help the many across #PuertoRico who remain in desperate need after #HurricaneMaria. See how here: …'], 'highest': [3, 'RT theCEI: THANK YOU to rubendiazjr and the NY Hispanic Clergy for organizing an amazing event last week in support of PuertoRico! 🇵🇷❤️…']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.