【问题标题】:How to get the most common in a list of strings [duplicate]如何在字符串列表中获得最常见的[重复]
【发布时间】:2022-01-22 05:19:52
【问题描述】:

所以我收到了来自 api (openweathermap.org) 的响应,并且我将所有 {weather} 变量都放在了一个列表中。我试图在 ["Sunny", "Scattered clouds", "Rainy", "Scattered Clouds"] 中找到最常见的例子,但类似的东西。

我还想到了一种使用 for 循环和字典的方法:

listt = ["R","S","SC","SC"]
dictt = {}
for i in listt:
    dict[f"{i}"] +=1

但是……是的。我知道这行不通。我的意思是,我可以硬编码dictt,但我不知道 API 中的所有天气状况。 还有其他方法可以获取列表中最常见的字符串吗?

我正在使用来自 openweathermap.org 的 one-call api

【问题讨论】:

标签: python


【解决方案1】:

解决方案

(在 Python 2 和 3 中测试)

您可以使用字典来映射您提供的值。

然后获取字典中的key或者最常见的字符串,获取字典中最大值的key,像这样:(Reference)

listt = ["R","S","SC","SC"]
dictt = {}

for i in listt:
    # add to dictionary if it does not exist
    if i not in dictt:
        # this also does the same thing as 'dict[f"{i}"]' 
        dictt[i] = 1

    # update dictionary
    else:
        dictt[i] +=1

print(max(dictt))
# 'SC'

其他说明

  • @Fareed Khan 评论的可能是duplicate
  • 您还可以在 python 中使用 Counters(由 @Ederic Oytas 评论)

from collections import Counter

listt = ["R","S","SC","SC"]
print(max(Counter(listt)))
# 'SC'

【讨论】:

  • 这不会修复问题代码中的任何错误。它至少有一个名称和一个键错误。
  • @MisterMiyagi 道歉,刚刚发现错误。 'dictt' 是一个令人困惑的变量名:D
  • 好吧,for 循环不能像我所说的那样工作......所以 max 也不能工作...... aaaaand 与计数器相同。
  • @APickacks 对此感到抱歉...稍作调整即可:)
猜你喜欢
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 2014-11-04
  • 2018-07-29
  • 2022-01-25
相关资源
最近更新 更多