Python - 在列表列表中出现子字符串

时间:2012-11-05 05:56:07

标签: python python-3.x

我正在使用一个函数来搜索列表列表中的子字符串,作为列表中每个项目的前三个字符。例如,如果子字符串为'aaa'且列表列表为[['aaa111', 'aba123', 'aaa123'], ['aaa302', 'cad222']],我希望该函数返回百分比列表[66, 50],因为'aaa'出现在首先列出2/3次,并在第二列表中列出1/2次。到目前为止,我有:

def percentage(list_of_lists, substring):
    count = 0
    percentage = []
    for item in list_of_lists:
        for i in item:
            if substring == i[0:3]:
                count += 1
        percentage.append(int(count / len(item) * 100))
    return percentage

我知道我的代码可能过多,但我只是得到了Python的要点所以我并不担心。

>>> percentage([['aaa111', 'aba123', 'aaa123'], ['aaa302', 'cad222']], 'aaa')
[66, 150]

如何在list_of_lists中按列表列出计数?

3 个答案:

答案 0 :(得分:5)

两件事......

  1. 重置每个循环的count
  2. 使用float进行除法(仅适用于python 2.x)
  3. 我更改了count - > 0.0

    def percentage(list_of_lists, substring):
        percentage = []
        for item in list_of_lists:
            count = 0.0
            for i in item:
                if substring == i[0:3]:
                    count += 1
            percentage.append(int(count / len(item) * 100))
        return percentage
    
    # Test
    In [17]: l = [['aaa111', 'aba123', 'aaa123'], ['aaa302', 'cad222']]
    In [18]: s = 'aaa'
    In [19]: percentage(l,s)
    Out[19]: [66, 50]
    

答案 1 :(得分:2)

使用lambdamap函数的解决方案:

>>> [(sum(map(lambda z: "aaa" in z,z))*100/len(z)) for z in [y for y in [['aaa111', 'aba123', 'aaa123'], ['aaa302', 'cad222']]]]
[66, 50]

答案 2 :(得分:1)

此修改后的代码适用于我:

def percentage(list_of_lists, substring):
    count = 0
    percentage = []
    for item in list_of_lists:
        for i in item:
            if substring == i[0:3]:
                count += 1
        percentage.append(int(count / len(item) * 100))
        count = 0
    return percentage