尝试在不使用任何内置函数的情况下查找列表中出现的次数。还有什么其他方法?我的下面的代码不起作用

问题描述 投票:-2回答:4

尝试在不使用任何内置函数的情况下查找列表中出现的次数。以下代码不起作用

a = [1,1,2,3,4,4,5]
for i in a:
    c = 0
    if a[i] == a[i]+1:
        c =+1
        print(c)
python python-3.x
4个回答
2
投票

Num是您要寻找的号码。不确定这是不是你想要的。

a = [1,1,1,1,2,3,4,4,5]
c = 0 
num = 1;
for i in a:
    if i == num:
        c += 1
print(c)

或这个

a = [1,1,1,1,2,3,4,4,5]
b = []
t = 0
x = 0 
while t < len(a):
  c = 0
  temp = a
  for i in temp:
    if i == x:
      c += 1
  b.append(c)
  t += c
  x += 1
print(b)

输出[0,4,1,1,2,1]


0
投票

我看到这样做的一个丑陋但几乎有趣的方法是循环遍历列表,找到最大值,创建该大小的列表,然后在达到您的值时重新浏览并增加新列表中的索引。

a = [1,1,2,3,4,4,5]

max = -1
for i in a:
    if i > max:
        max = i

long_list = [0] * (max + 1) #create the list of the max size

for i in a:
    long_list[i] = long_list[i] + 1

print(long_list)

这里的输出是:[0,2,1,1,2,1]

再一次,这根本不是空间效率,但我喜欢实现,因为我认为它很有趣。

此实现的问题是,如果您有一个列表,如[1,2,3,545543,34]。然后你的输出会有点狂野的打印,浪费了很多空间。


0
投票

我很惊讶地看到3个答案没有使用字典来解决这个问题。

l = [1, 1, 2, 3, 4, 4, 5]
counts = {}
for x in l:
    if x in counts:
        counts[x] += 1
    else:
        counts[x] = 1

在运行上述代码之后,count计算列表l中每个项目的出现次数,其中项目本身(在这种情况下为数字)作为键。

>>> l = [1, 1, 2, 3, 4, 4, 5]
>>> counts = {}
>>> for x in l:
...     if x in counts:
...         counts[x] += 1
...     else:
...         counts[x] = 1
...
>>> counts
{1: 2, 2: 1, 3: 1, 4: 2, 5: 1}

0
投票

令人惊讶的是,如果你知道max,这很容易。我假设你的min=0max=5(你可以改变)

a = [1,1,2,3,4,4,5]
freq=[0]*6 # assume 5 is your max
for i in a:
    freq[i] += 1

print(freq)
print(freq[num])

DEFAULTDICT

如果你不知道max

from collections import defaultdict
a = [1,1,2,3,4,4,5,5,5,5,5,5,5]
d=defaultdict(int)
for i in a:
    d[i] +=1
print(d)
© www.soinside.com 2019 - 2024. All rights reserved.