Python Count函数的应用

时间:2023-03-09 09:59:27
Python Count函数的应用

Python Count函数的应用

通过LeetCode Origin:https://leetcode-cn.com/problems/robot-return-to-origin/

  • 学会了Python中直接对字符串中元素计数:

    str.count(element, start=0, end=len(str))

    count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

    • sub -- 搜索的子字符串
    • start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
    • end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
  • 对于list,也有相应的count()内置函数:

    对于一个list arr,arr.count(target)返回target元素在arr这个list中出现过多少次

    arr = [1, 2, 2, 2, 3]
    print(arr.count(2)) >>> 3
  • 位运算快速输出

    return a == b and c == d

    代码简洁一点