How would you translate this from Perl to Python?

后端 未结 8 2222
忘了有多久
忘了有多久 2021-02-08 03:01

I\'ve got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it\'s never seen it before) or otherwise, it appends some letters to make it uni

8条回答
  •  广开言路
    2021-02-08 03:38

    Does the suffix have to be letters like that?

    from itertools import count
    def unique(timestamp): 
      if timestamp in unique.ts.keys():
        return timestamp + '.' + str(unique.ts[timestamp].next())
      else:
        unique.ts[timestamp] = count()
        return timestamp
    unique.ts = {}
    

    You can define a different count if you want the letters back.

    This isn't the same as your perl code, though.

    • It keeps a dict around so if you have lots of unique timestamps then you'll use lots of memory.
    • It handles out of order calls, which the original doesn't (i.e. u(1), u(2), u(1)).

提交回复
热议问题