简体   繁体   English

如何枚举/压缩为lambda

[英]how to enumerate / zip as lambda

Is there a way to replace the for-loop in the groupList function with a lambda function, perhaps with map() , in Python 3. 有没有一种方法可以用lambda函数(也许在Python 3中用map()替换groupList函数中的for循环。

def groupList(input_list, output_list=[]):
    for i, (v, w) in enumerate(zip(input_list[:-2], input_list[2:])):
        output_list.append(f'{input_list[i]} {input_list[i+1]} {input_list[i+2]}')
    return output_list

print(groupList(['A', 'B', 'C', 'D', 'E', 'F', 'G']))

(Output from the groupList function would be ['AB C', 'BC D', 'CD E', 'DE F', 'EF G'] ) groupList函数的输出为['AB C', 'BC D', 'CD E', 'DE F', 'EF G']

Solution 1: 解决方案1:

def groupList(input_list):
    return [' '.join(input_list[i:i+3]) for i in range(len(input_list) - 2)]

Solution 2: 解决方案2:

def groupList(input_list):
    return list(map(' '.join, (input_list[i:i+3] for i in range(len(input_list) - 2))))

Besides the previous solutions, a more efficient (but less concise) solution is to compute a full concatenation first and then slice it. 除了先前的解决方案,一种更有效(但不太简洁)的解决方案是先计算完整的串联,然后对其进行切片。

from itertools import accumulate

def groupList(input_list):
    full_concat = ' '.join(input_list)
    idx = [0]
    idx.extend(accumulate(len(s) + 1 for s in input_list))
    return [full_concat[idx[i]:idx[i+3]-1] for i in range(len(idx) - 3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM