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

Python-在列表列表中出现子字符串,python,python-3.x,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 =

我正在使用一个函数,该函数将搜索列表中的子字符串,作为列表中每个项目的前三个字符。例如,如果子字符串是
'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]
如何在我的列表中一个列表一个列表地计数?

两件事

  • 重置每个循环的
    计数
  • 使用浮点进行除法(仅适用于python 2.x)
  • 我更改了
    计数
    ->
    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]
    

    这段修改过的代码适合我:

    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
    

    使用
    lambda
    map
    功能的解决方案:

    >>> [(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]
    

    总是比我想象的容易。。。谢谢!嗯。当只需要调整一行时很有趣:-)如果子字符串长度发生变化,最好使用
    i.startswith(substring)
    而不是
    substring==i[0:3]: