在多个列表中查找最大值

时间:2013-11-25 17:37:45

标签: python

所以我有2个列表,其中包含一年中哪些人访问伦敦和悉尼

names=['james','lin','mark','james','line','mark'.'lin','mark','james','mark']
dates[london]=['2-3-1999','3-3-1999','23-7-1999','25-12-1999','13-6-1999'.'1-1-1999'.'5-3-1999','10-4-1999','9-11-1999','23-4-1999']
dates[sydney]=['21-1-2011', '24-1-2011', '24-1-2011', '02-02-2011', '03-02-2011', '19-4-2011', '14-5-2011', '06-11-2011', '07-3-2011']


# the above dates are in the form  day:month:year

我怎样才能使用上面的列表来查找这些人中哪个月的游客最多#answer是第三个月。

我相信我必须使用某种索引,但我不确定是否可以完成

3 个答案:

答案 0 :(得分:1)

l = [map(lambda x: x.split("-")[1], dates1 + dates2).count(str(mon)) for mon in range(1, 13)]
result = l.index(max(l)) + 1

,其中

dates1 + dates2 - 是一个由两个输入列表组成的列表(我不确定这是你想要的,但是..)

lambda x: x.split("-")[1] - 表示我们创建一个函数,它接受字符串,用“ - ”拆分并返回第二部分(月)

map(f(), coll) - 表示我们将函数f应用于coll集合的每个成员并获取结果

range(1, 13)给了我们[1,2,3,4,5,6,7,8,9,10,11,12] - 月数

[f(x) for x in collection]是列表理解(类似于map()的smth) - 生成列表的便捷功能 - 在此步骤中,我们将每个月的频率放在一个列表中

l.index(max(l)) + 1 - 现在我们所需要的只是查找max元素并返回其索引。

答案 1 :(得分:0)

一个简单的解决方案,如果在列表中保存包含您提供的列表中的金额的12个月,例如:

# create a list with 12 positions initialized with zero, (months)
months = [0]*12

def count_months(dates):
  # list contains the specified dates      
  for item in dates:
    # first we split by the '-' character and then get the second : is the month
    _month = int(item.split('-')[1])
    month[_month] += 1    

london = ['2-3-1999','3-3-1999','23-7-1999','25-12-1999','13-6-1999'.'1-1-1999'.'5-3-1999','10-4-1999','9-11-1999','23-4-1999']
count_months(london)

#to find the most occur we only need to find the max of the list
max = -1
for i in range(0,13):
  if month[i] > max:
    max = a[i]
    maxIndex = i

print maxIndex

对于各种列表,您只需将列表传递给之前解释过的代码,然后查找最大元素。

答案 2 :(得分:0)

只需浏览您的列表并找到重复的最大值 使用string代替列表int中的a,例如:

import random
a = [ random.randrange(10) for i in range(30)]
max = 0
value = ''
for i in set(a):
    if max < a.count(i):
      max = a.count(i)
      value = i
print("value: {0}\ntimes: {1}".format(value, max))