Python list comprehension - access last created element?

后端 未结 7 2001
无人共我
无人共我 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:27

    You could use a helper object to store all the internal state while iterating over the sequence:

    class Encryption:
      def __init__(self, key, init_value):
        self.key = key
        self.previous = init_value
      def next(self, element):
        self.previous = element ^ self.previous ^ self.key
        return self.previous
    
    enc = Encryption(...)
    cipher = [enc.next(e) for e in message]
    

    That being said, adding the previously encrypted element into the xor doesn't make your algorithm any harder to break than just xor'ing every element with the key. An attacker can just xor any character in the cipher text with the previous encrypted character and so cancel out the xor that was done during encryption.

提交回复
热议问题