gpt4 book ai didi

python - 如何根据垂直位置重命名 python 列表列表中的重复元素?

转载 作者:行者123 更新时间:2023-12-05 03:55:10 31 4
gpt4 key购买 nike

我有一个这样的列表列表:

listofLists = [
['a', 'b', 'e'],
['a', 'd'],
['a', 'c'],
['a', 'b', 'c', 'e'],
['a', 'e', 'c', 'f']
]

我怎样才能垂直读取这个元素列表并重命名重复项,并以递增顺序将数字附加到元素?输出列表必须保持相同的顺序。

例如,'e' 的第一个位置在列表 ['a', 'e', 'c', 'f'] 中的索引 1 处,它应该保持原样。 'e' 的下一个位置在列表 ['a', 'b', 'e'] 中的索引 2 处,应将其重命名为 'e1'。 'e' 的最后位置在列表 ['a', 'b', 'c', 'e'] 中,应重命名为 'e3'

所需的输出应该是:

requiredOutput = [['a', 'b', 'e1'],
['a', 'd'],
['a', 'c'],
['a', 'b', 'c1', 'e2'],
['a', 'e', 'c1', 'f']]

我尝试过的代码如下,通过检查转置列表。但它没有给我所需的输出,因为我的代码更改了列表的当前元素。我不知道这是否是问题陈述的正确方法。

transformedListOfTuples = list(zip_longest(*listofLists))
transformedListOfList= [list(x) for x in transformedListOfTuples]
for i in range(0, len(listofLists)):
for j in range(0, len(listofLists[i])):
pos = -1
for z in range(0, len(transformedListOfList)):
if listofLists[i][j] in transformedListOfList[z]:
pos = pos + 1
if pos == 0:
continue
elif pos > 0:
listofLists[i][j] = listofLists[i][j] + str(pos)
elif listofLists[i][j] not in transformedListOfList[z]:
continue

最佳答案

这个怎么样:

arr = [
['a', 'b', 'e'],
['a', 'd'],
['a', 'c'],
['a', 'b', 'c', 'e'],
['a', 'e', 'c', 'f']
]

listOfRepeated = []
max_len = 0

for i in range(0, len(arr)):
if max_len < len(arr[i]):
max_len = len(arr[i])

for j in range(0, max_len):
list_to_add = []
for i in range(0, len(arr)):
if j < len(arr[i]):
val = arr[i][j]
# For each iteration of `i`, you'll go down the group

if not val in list_to_add:
list_to_add.append(val)

count = listOfRepeated.count(val)
if count > 0:
arr[i][j] = ""+str(val)+""+str(count)

for element in list_to_add:
listOfRepeated.append(element)

for list in arr:
print(list)

输出:

['a', 'b', 'e1']
['a', 'd']
['a', 'c']
['a', 'b', 'c1', 'e2']
['a', 'e', 'c1', 'f']

说明:

j 是水平方向的计数器,i 是向下组的计数器。每个元素都出现在 arr[i][j]

list_to_add 是一个包含特定组的每个唯一字符的列表

listOfRepeated 是到目前为止已看到的每个元素的列表。如果您在 listOfRepeated 中出现过一次,则意味着您当前的组是第一个具有该字符的组。如果不止一次,则意味着您需要在字符后添加一个数字。

关于python - 如何根据垂直位置重命名 python 列表列表中的重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389398/

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