1

我有类别

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,而 Banana 的结果是 1910-1919。

我已经搞砸了几个小时。我曾尝试将它们放入集合并使用键和值对其进行配置,但我所做的一切都没有奏效。我非常感谢您的帮助。谢谢!

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

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

4

2 回答 2

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'
于 2013-04-13T03:50:17.970 回答
1

以下是您如何获得"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
于 2013-04-13T03:38:25.743 回答