python - 查找排名最高的值

标签 python

我有类别

Rank   Fruits:      Vegetable:    Years:
1      Apple        Lettuce       1900-1909      
2      Pineapple    Carrot        1900-1909
3      Orange       Potato        1900-1909
4      Banana       Beans         1900-1909
 Rank   Fruits:      Vegetable:    Years:
 1      Banana       Carrot        1910-1919      
 2      Orange       Potato        1910-1919
 3      Apple        Beans         1910-1919
 4      Pineapple    Lettuce       1910-1919

这是我上面给出的数据。我想找到水果香蕉何时最受欢迎(也就是排名最接近 1 的时间)。我还需要找到 Carrot 何时最受欢迎。

例如,我需要它来显示胡萝卜的结果是 1910-1919 年,香蕉的结果是 1910-1919 年。

我已经在这个问题上折腾了好几个小时了。我尝试将它们放入集合中并使用键和值对其进行配置,但我所做的一切都不起作用。我非常感谢您的帮助。谢谢!

def getHighRank(data):
    nameSet=()
    nameList=[]
    for names in data:
        nameList.append[1]
        nameList.append[2]

这就是我到目前为止所拥有的。我尝试将水果和蔬菜放入一个列表中。我正在考虑将其转换为一套,但我现在对做什么一无所知。

最佳答案

>>> d = {}
>>> with open('test.txt') as f:
        print f.read() # shows the file structure


Rank   Fruits:      Vegetable:    Years:
1      Apple        Lettuce       1900-1909      
2      Pineapple    Carrot        1900-1909
3      Orange       Potato        1900-1909
4      Banana       Beans         1900-1909
Rank   Fruits:      Vegetable:    Years:
1      Banana       Carrot        1910-1919      
2      Orange       Potato        1910-1919
3      Apple        Beans         1910-1919
4      Pineapple    Lettuce       1910-1919
>>> with open('test.txt') as f:
        for line in f:
            try:
                rank, fruit, vegetable, year = line.split()
                for k in (fruit, vegetable): # for both the fruit and veg
                    t = (rank, year) # tuple of rank and year
                    d[k] = min(d.get(k, t), t) # set it to the min (rank, year)
            except: # skip headers
                pass


>>> d['Apple'] # fast lookup
('1', '1900-1909')
>>> d['Apple'][1]
'1900-1909'
>>> d['Carrot'][1]
'1910-1919'
>>> d['Banana'][1]
'1910-1919'

关于python - 查找排名最高的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983425/

相关文章:

python - 在 numpy 中使用二维索引对一维数组进行子采样

python - 什么是 Vaex 函数将字符串解析为 datetime64,相当于 pandas to_datetime,允许自定义格式?

python - imp.reload - NoneType 对象没有属性 'name'

python - 导入错误: No module named 'app'

python - 使用DataNitro,如何打印python循环到excel,确保打印23行后,打印移动到相邻列?

python - 使用 "is"来检查变量中包含哪个函数是个好主意吗?

python - 使用 virtualenv 时我应该提交/bin 目录吗?

python - 为什么我在构建 python 时构建 sqlite3 失败?

python - 在 sympy 中进行符号集成的快速方法是什么

python - 在带有 unicode 文本的 python 中使用 jsbeautifier 时出错