gpt4 book ai didi

python - 列表中的编号重合

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:14 25 4
gpt4 key购买 nike

我有一个具有以下结构的列表:

A1, B2, C3, 66
A1, B2, C3, 00
A2, B2, C3, 77
A3, B3, C4, 44
A4, B4, C5, 11
A4, B4, C5, 12
A4, B4, C5, 13

我需要枚举唯一的 1-3 列元素以获得如下输出:

A1, B2, C3, 66, 1
A1, B2, C3, 00, 2
A2, B2, C3, 77, 1
A3, B3, C4, 44, 1
A4, B4, C5, 11, 1
A4, B4, C5, 12, 2
A4, B4, C5, 13, 3

如您所知,我希望第四列中的序号按 1-3 列中的唯一值排序。

看完说明,我得出的结论是需要用到collections模块。这是正确的决定吗?

我试试这个:

new = ['A1,B2,C3,66','A1,B2,C3,00','A2, B2, C3, 77','A3, B3, C4, 44','A4, B4, C5, 11','A4, B4, C5, 12','A4, B4, C5, 13']
test=[]
i = 0
for a in new:
i+=1
test.append('{},{}'.format(i, a))
print(test)
if a[i]!=a[i-1]:
continue

最佳答案

你可以使用itertools.groupby:

import itertools
import re
new = ['A1,B2,C3,66','A1,B2,C3,00','A2, B2, C3, 77','A3, B3, C4, 44','A4, B4, C5, 11','A4, B4, C5, 12','A4, B4, C5, 13']
n = map(lambda x:re.split(',\s*', x), new)
s = [list(b) for _, b in itertools.groupby(n, key=lambda x:x[:-1])]
last_data = map(lambda x:', '.join(x[:-1]+[str(x[-1])]), [i for b in [[b+[i] for i, b in enumerate(c, start=1)] for c in s] for i in b])

输出:

['A1, B2, C3, 66, 1', 
'A1, B2, C3, 00, 2',
'A2, B2, C3, 77, 1',
'A3, B3, C4, 44, 1',
'A4, B4, C5, 11, 1',
'A4, B4, C5, 12, 2',
'A4, B4, C5, 13, 3']

关于python - 列表中的编号重合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49261197/

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