获取python列表中的所有字符串

时间:2016-09-27 14:15:05

标签: python list

我有这份清单

Console.Write

我想提取所有字符串perse我不知道这些字符串可能是什么,并计算每个字符串出现。 是否有一个简单的循环指令来做到这一点?

3 个答案:

答案 0 :(得分:6)

我不确定是否理解了你的问题(单词" perse"我不知道)如果你想计算正常和异常的字符串的出现,我建议:

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

输出:

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

答案 1 :(得分: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)

答案 2 :(得分:0)

以下是解决方案:

parentNode.insertBefore(newChild, refChild)

变量count = 0 str_list = [] for arr in a: for ele in arr: if isinstance(ele, str): count += 1 str_list.append(ele) print count 保存列表a中每个列表中的字符串总数。虽然count将保留所有字符串

以下是repl.it上的代码段:documentations