gpt4 book ai didi

python - 在Python中迭代列表并连接字母顺序

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:43 24 4
gpt4 key购买 nike

我试图迭代一个列表,并为列表中的每个元素分配一个按字母顺序排列的字母,如果有重复项,则为其分配字母表中的下一个字母以获得唯一的项目。

sequence = [0, 1, 2, 3, 1, 4, 2, 1]
unique_seq = [0A, 1A, 2A, 3A, 1B, 4A, 2B, 1C]

我尝试生成这样的字母列表:

alpha = list(map(chr, range(65, 91)))

然后我想像这样迭代序列:

for i in sequence:
unique_seq.append(i) for i in sequence if i not in unique_seq else...

我不知道如何处理剩下的事情......

谢谢,

最佳答案

这是一个解决方案,适用于无限大小和无限重复次数的序列(内存允许)

def increment_item(item = 'A'):
'''
Given a character sequence item, produces the next item in the character sequence set

:type item: str
:param item: The character sequence item to increment
:rtype: str
:return: The next element in the sequence. EX: item='A', return ='B'. item='Z', return ='AA'

'''
next_char = [ord(char) for char in item]
next_char[-1] += 1
for index in xrange(len(next_char)-1, -1, -1):
if next_char[index] > ord('Z'):
next_char[index] = ord('A')
if index > 0:
next_char[index-1] += 1
else:
next_char.append(ord('A'))
return ''.join((chr(char) for char in next_char))

def char_generator(start = 'A'):
'''
A generator which yields the next item in the character sequence every time next() is called

:type start: str
:param start: The starting item for the generator sequence

'''
current = start
yield start
while True:
current = increment_item(current)
yield current


def build_unique_sequence(sequence):
'''
Given an input sequence, returns the same sequence with characters
appended such that every element in the returned sequence is unique

:type sequence: list
:param sequence: The sequence to make unique
:rtype: list
:return: The resultant unique sequence. EX: sequence = [0, 1, 2, 3, 1, 4, 2, 1], return = ['0A', '1A', '2A', '3A', '1B', '4A', '2B', '1C']

'''
key_set = dict([item, char_generator()] for item in set(sequence))
return map(lambda item:'{}{}'.format(item, key_set[item].next()), sequence)

结果是:

>>> build_unique_sequence([0, 1, 2, 3, 1, 4, 2, 1])
['0A', '1A', '2A', '3A', '1B', '4A', '2B', '1C']

关于python - 在Python中迭代列表并连接字母顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23259300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com