Python list comprehension - access last created element?

后端 未结 7 2008
无人共我
无人共我 2020-12-14 17:31

Is it possible to access the previous element generated in a list comprehension.

I am working on some toy encryption stuff. Given the key as an arbitrarily large in

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 18:16

    You could have done this using reduce(). It's not list comprehension, but it's the functional style approach:

    cipher = []
    def f(previous, element):
        previous = element ^ previous ^ key
        cipher.append(previous)
        return previous
    reduce(f, message, initialization_value)
    

    It isn't any prettier than the plain loop in this case though.

提交回复
热议问题