抓取所有的字符串列表

问题描述:

的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)' –

如果你要计算出现的次数,并跟踪串的,循环的每个项目,并把它添加到字典

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) 

我不知道已经明白你的问题(字“深灰色“是未知的我)如果你想数串正常和异常的发生,我提议:

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

下面是解:

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