Python 查找具有最高秩的值

Python 查找具有最高秩的值,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: V

我有分类

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的时候)。我还需要找出胡萝卜什么时候最受欢迎

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

我已经胡闹了好几个小时了。我试着把它们放在一组中,并用键和值进行配置,但我所做的一切都不起作用。我真的很感激你的帮助。谢谢

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

这就是我目前所拥有的。我试着把水果和蔬菜放在一张单子上。我想把它转换成一个集合,但我现在不知道该怎么做。

下面是如何得到
“Carrot”
的结果。您应该能够从那里继续:

with open('filename') as f:
    print min(row.split() for row in f if row[:1].isdigit() 
                                       and 'Carrot' in row)[3]
# prints: 1910-1919

请分享你所拥有的,以便我们纠正你的错误。没有人会为你提供一个完整的解决方案。这是两个独立的文件吗?不是两个独立的文件都是一个文件,我会打印我到目前为止的内容。一秒钟。你的数据没有意义。它每年只给出一个值,这大大限制了它的实用性(例如,1900-1909总是排名1)。看起来你想在数据表中添加三个维度(日期、等级和水果/蔬菜),但却试图将其分为两个维度。天哪,一秒一秒的时间完全搞糟了,我会把它改成它应该是什么,贝蒂斯很可能会混淆OP,如果你看他的起始代码,阿门,哈哈,我一点也不明白XD@jamylak--这很可能是真的,但我们不是都在这里学习新东西吗:)
>>> 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'