2017-06-02 56 views
0

我有這樣一段代碼:如何將for循環轉換爲Python中的理解列表?

unique_char = np.zeros(26,dtype=np.int); 
    for char in s1: 
     unique_char[np.int(ord(char)-97)] += 1 

這是整個代碼:

def check_permutation(str1,str2): 

    if str1 is None or str2 is None: 
      return False 
    if len(str1) != len(str2): 
      return False 

    s1 = str1.lower() 
    s2 = str2.lower() 

    unique_char = np.zeros(26,dtype=np.int); 

    for char in s1: 
     unique_char[np.int(ord(char)-97)] += 1 

    for char in s1: 
     unique_char[np.int(ord(char)-97)] -= 1 

    for x in unique_char: 
     if unique_char[x] != 0: 
      return False 
    return True 

我怎麼能轉換成一個修真名單呢?

謝謝!

+2

您似乎試圖計算字符串中字符出現次數 - 您是否考慮過使用[Counter](https://docs.python.org/2/library/collections.html#collections.Counter) ? – asongtoruin

+0

你能粘貼完整的代碼和你想要的輸入/輸出的描述嗎? s1中有什麼? – papey

+5

你可以,但它不會有效。在計數時,不要使用列表理解,使用'Counter()'。 –

回答

1

你還沒有提供s1的例子,所以我用我自己的。與您的代碼開始:

import numpy as np 

s1='teststring' 

unique_char = np.zeros(26, dtype=np.int) 

for char in s1: 
    unique_char[np.int(ord(char) - 97)] += 1 

我們得到的

[0 0 0 0 1 0 1 0 1 0 0 0 0 1 0 0 0 1 2 3 0 0 0 0 0 0] 

一個numpy的數組如果你真的想做它作爲一個列表理解,你可以做類似下面的結果:

unique_char = [sum(1 for c in s1 if ord(c)-97 ==i) for i, x in enumerate(unique_char)] 

這將返回形式的列表的結果:

[0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0] 

但是,如果您要計算字符串中的字符,最有效的方法是使用計數器。

from collections import Counter 

unique_char = Counter(s1) 

這將返回形式的字典子類:

Counter({'t': 3, 's': 2, 'e': 1, 'g': 1, 'i': 1, 'n': 1, 'r': 1}) 

若要將此所提供的例子,你可以爲每個字符串Counter,然後檢查是否每返回相同的值所有的字母:

from collections import Counter 

def check_permutation(str1,str2): 
    if str1 is None or str2 is None: 
     return False 
    if len(str1) != len(str2): 
     return False 

    s1 = Counter(str1.lower()) 
    s2 = Counter(str2.lower()) 

    all_chars = set(s1.keys() + s2.keys()) 

    for k in all_chars: 
     if s1.get(k, 0) != s2.get(k, 0): 
      return False 

    return True 

print check_permutation('test', 'tset') 
print check_permutation('test', 'tsat') 
print check_permutation('test', 'tttt') 

此打印:

True 
False 
False