使用python的数组“myList”中有多少个5

2024-06-01 20:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了一个随机生成100个数字的代码,并将所有数字放入一个数组中。我想知道一个命令或代码,它可以告诉我在生成数组后数组中有多少个5(或任何数字)。
这是我目前的代码>;>

import random
x = 1
def rand():
    return random.randrange(0,10,1) #a random number between 0 and 9
myList = []
while (x != 100):
    x=x+1
    y = rand()
    myList.append(y)

最后,我需要一个命令来告诉我5的数字,比如>;>

getNumber.of(5) from myList

我还需要一个输出,显示位置也。类似于>;>

7 (5's) at: myList[12], myList[20], myList[27], myList[33], myList[59], myList[74], myList[90]

Tags: and代码import命令gtnumberreturndef
3条回答

给定一个数字列表mylist,您可以通过以下方法获得5出现的位置:

[a for (a,b) in enumerate(mylist) if b == 5]

Python列表有一个count方法:

>>> myList = [1,2,3,4,5,5,4,5,6,5]
>>> myList.count(5)
4

这将让您开始索引:

>>> start = 0
>>> indexes = []
>>> for _ in xrange(myList.count(5)):
...     i = myList.index(5, start)
...     indexes.append(i)
...     start = i + 1
... 
>>> indexes
[4, 5, 7, 9]

您可以使用生成器和内置的sum解决此问题:

def getNumberOf(candidate, mylist):
    """ Returns the number of appearances of candidate in mylist """
    return sum(1 for number in mylist if number==candidate)

def getPositionOf(candidate, mylist):
    """ Returns a list of indexes where the candidate appears in mylist"""
    return [index for index, value in enumerate(mylist) if value==candidate]

相关问题 更多 >