在多个列表中查找最大出现次数

2024-03-29 10:24:12 发布

您现在位置: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[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

我怎样才能用上面的列表来找出哪一个月的访客最多?答案是第三个月。你知道吗

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


Tags: theinformnameslineareabovedates
3条回答

只需浏览一下你的列表,找出重复的最大价值 使用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))

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

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

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

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

相关问题 更多 >