2016-09-27 41 views
1

的Python列表我已經列出抓取所有的字符串列表

a = [[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'ab 
normal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal'],[1,2,3,4,' 
abnormal']] 

我想提取所有字符串的這個名單Perse的我不知道這些字符串可能,並計算每個字符串次數。 有沒有簡單的循環指令來做到這一點?

+2

只需使用一個嵌套的'for'循環,並檢查每一個元素'isinstance(元素,STR)' –

回答

2

如果你要計算出現的次數,並跟蹤串的,循環的每個項目,並把它添加到字典

a = [[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal']] 

new={} 
for b in a: 
    for item in b: 
     if type(item) is str: 
      if item in new: 
       new[item]+=1 
      else: 
       new[item]=1 
print(new) 
6

我不知道已經明白你的問題(字「深灰色「是未知的我)如果你想數串正常和異常的發生,我提議:

from collections import Counter 
Counter([elt[4] for elt in a]) 

輸出:

Counter({'abnormal': 5, 'normal': 3}) 
+0

也許這本來是與「perse」:https://en.wiktionary.org/wiki/per_se – VPfB

0

下面是解:

count = 0 
str_list = [] 
for arr in a: 
    for ele in arr: 
     if isinstance(ele, str): 
      count += 1 
      str_list.append(ele) 
print count 

可變count保存字符串在列表內的每個列表的總數。雖然str_list將持有的所有字符串

這裏是repl.it代碼片段:https://repl.it/Di9L

相關問題