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

标签 python python-3.x list

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

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/

相关文章:

python - AWS Cloudformation,使用 Python 3 从键获取值的最佳方式

python - tf.expand_dims 究竟对向量做了什么,为什么即使矩阵形状不同也可以将结果加在一起?

python - 列表矩阵 - Python

python - 切换到 Django 中的另一个数据库

python - 使用 pyspark 创建年份列

python - 类型检查 : an iterable type that is not a string

python - 检查元素是否在所有列表中一起出现?

Python - 使用 pywin32 从不同地址发送 Outlook 电子邮件

python相当于clojure的partition-all?

python - 如何根据索引添加子列表的元素 - Python