我正在编写一个包含数字列表的函数,我需要找到一种方法来计数数字1和2的出现情况,只对列表的最后3个值进行计数。
我显然知道.count()函数,但我想知道是否有一种方法只在给定的索引之间使用,在本例中,索引是((len(history-3), (len(history)),history是一个仅包含值1和2的列表。
TL;DR:是一种在给定索引之间计数列表中出现的值的方法。
发布于 2019-02-25 18:19:17
正如洛基·李( Rocky )所建议的那样,你可以通过切片history[-3:]来获得列表的最后三个元素。然后,您可以使用切片上的count函数来获取列表中最后三个点中1和2的计数。
例如:
>>> history = [1, 2, 1, 2, 1, 2, 1, 2, 1]
>>> count_1 = history[-3:].count(1)
>>> count_2 = history[-3:].count(2)
>>> count_1
2
>>> count_2
1发布于 2019-02-25 18:17:06
使用负切片获取最后的n值,并使用count()进行计数。
lst[-3:].count(2) # counts number of 2 from last three elements of list lst.
lst[-3:].count(1) # counts number of 1 from last three elements of list lst.List有内置的count方法来计算值.
发布于 2019-02-25 18:17:36
您可以将列表切片,然后计数。
arr = [2,1,3,3]
arr[-3:].count(3) # 2您可以对索引进行完全相同的操作,如指示的here。
arr[start:stop].count(3) # items start through stop-1
arr[start:].count(3) # items start through the rest of the array
arr[:stop].count(3) # items from the beginning through stop-1
arr[:].count(3) # a copy of the whole array我希望这有什么用。
https://stackoverflow.com/questions/54872308
复制相似问题