C到Python Anagrams

Cod*_*lus 0 c python indexing

我正在努力学习Python.考虑C中这个简单的anagram检查器:

bool are_anagrams(const char* str1, const char* str2)
{
  int str1_count[NUM_CHARS] = {0};
  int str2_count[NUM_CHARS] = {0};

  for(int i = 0; i < strlen(str1); i++)
  {
    str1_count[str1[i] - 'a']++;
  } 
  for(int i = 0; i < strlen(str2); i++)
  {
    str2_count[str2[i] - 'a']++;
  }

  for(int i = 0; i < NUM_CHARS; i++)
  {
    if(str1_count[i] != str2_count[i])
      { return false; }
  }

  return true;
}
Run Code Online (Sandbox Code Playgroud)

具体来说,如何str1_count[str2[i] - 'a']++在Python中完成这一行?

Ign*_*ams 5

具体来说,如何str1_count[str2[i] - 'a']++在Python中完成这一行?

事实并非如此.Python有dict处理这样的事情.

str1_count = {}
 ...
str1_count[char2] += 1
Run Code Online (Sandbox Code Playgroud)

虽然collections.defaultdict通常用于处理它是新密钥的情况.

str1_count = collections.defaultdict(int)
Run Code Online (Sandbox Code Playgroud)