获取python列表中的所有字符串
我有这张名单获取python列表中的所有字符串,python,list,Python,List,我有这张名单 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']] 我想提取所有的字符串,因为我不知道这些字符串可能是什么,并计算每个字符串的出现次数。 是否有一个简单的循环指令来实现这一点 如果要计算出现的次数
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']]
我想提取所有的字符串,因为我不知道这些字符串可能是什么,并计算每个字符串的出现次数。
是否有一个简单的循环指令来实现这一点 如果要计算出现的次数并跟踪字符串,请循环每个项目并将其添加到字典中
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)
如果要计算出现的次数并跟踪字符串,请循环每个项并将其添加到字典中
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)
我不确定是否理解了您的问题单词perse我不知道如果您想计算字符串正常和异常的发生率,我建议:
from collections import Counter
Counter([elt[4] for elt in a])
产出:
Counter({'abnormal': 5, 'normal': 3})
我不确定是否理解了您的问题单词perse我不知道如果您想计算字符串正常和异常的发生率,我建议:
from collections import Counter
Counter([elt[4] for elt in a])
产出:
Counter({'abnormal': 5, 'normal': 3})
以下是解决方案:
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保存列表a中每个列表中的字符串总数。而stru列表将保存所有字符串
以下是repl.it上的代码片段:以下是解决方案:
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保存列表a中每个列表中的字符串总数。而stru列表将保存所有字符串
以下是repl.it上的代码片段:只需使用嵌套的for循环并检查每个元素是否为instanceElement,str必须使用嵌套的for循环并检查每个元素是否为instanceElement,strMaybe这意味着perse:可能这意味着perse: