Python 在多个列表中查找最大发生次数

Python 在多个列表中查找最大发生次数,python,Python,因此,我有两个清单,其中包括每年哪一天个人访问伦敦和悉尼 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[syd

因此,我有两个清单,其中包括每年哪一天个人访问伦敦和悉尼

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
我怎样才能利用上面的列表来找出哪一个月的访客最多?答案是第三个月


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

如果将您提供的列表中的金额保存在一个包含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
对于各种列表,您只需将列表传递给前面解释的代码之类的方法,然后fin max元素

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
集合的每个成员,并获得结果集合

范围(1,13)
给出[1,2,3,4,5,6,7,8,9,10,11,12]-月数

[f(x)代表集合中的x]
是列表理解(类似于map())-生成列表的方便功能-在这一步中,我们在一个列表中有每月的频率


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

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

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))
随机导入
a=[random.randrange(10)表示范围(30)中的i]
最大值=0
值=“”
对于集合(a)中的i:
如果最大值
欢迎来到StackOverflow!这听起来像是个家庭作业问题。。。你试过什么?打印(dates.index(max(dates)))我试过了,但没有找到正确的答案。如果你能在问题中提供预期的结果,那会很有帮助。预期的结果应该是3Is
dates
a dictionary?你写的不是有效的语法。如果它是一本字典,它应该是
日期['london']
日期['sydney']
。确切地说,
日期(london)
是什么?它只是用户以前提供的列表中的一个示例,必须适合这项工作。你可以从这个问题中想到一个列表,不,不是。这不是有效的python语法。@rantanplan
function(argument)
是有效语法。@l4mpi哦,我不知道OP的目的是什么。我才不碰它呢,叫我疯子吧。。。但不知何故,我不认为OP会理解这一点。对不起,我不能把它放在一行:)然而,它可以很好地演示Python的功能特性。。尤其是如果OP对语言感兴趣,毫无疑问。我只是说这里可能需要一个解释,因为OP已经在与非常基本的概念作斗争。添加了一些解释