📜  Python程序在字符串中标记重复元素

📅  最后修改于: 2022-05-13 01:54:27.625000             🧑  作者: Mango

Python程序在字符串中标记重复元素

给定一个列表,任务是编写一个Python程序来标记具有渐进出现次数的元素的重复出现。

方法一:使用count() + enumerate() + list comprehension + slicing

在这种情况下,为了获得重复计数,将列表切片到当前元素索引,并使用 count() 和 append 计算该元素直到当前索引的出现计数。

Python3
# Python3 code to demonstrate working of
# Mark duplicate elements
# Using count() + enumerate() + list comprehension + slicing 
  
# initializing list
test_list = ["gfg", "is", "best", "gfg", 
             "best", "for", "all", "gfg"]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting count till current using count() and slicing
res = [val + str(test_list[:idx].count(val) + 1) if test_list.count(val) > 1 else val for idx,
       val in enumerate(test_list)]
  
# printing result
print("Duplicates marked List : " + str(res))


Python3
# Python3 code to demonstrate working of
# Mark duplicate elements
# Using map() + count() + lambda
  
# initializing list
test_list = ["gfg", "is", "best", "gfg", 
             "best", "for", "all", "gfg"]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting count till current using count() and slicing
res = list(map(lambda ele: ele[1] + str(test_list[ : ele[0]].count(ele[1]) + 1) if test_list.count(ele[1]) > 1 else ele[1],
               enumerate(test_list)))
  
# printing result
print("Duplicates marked List : " + str(res))


输出:

方法 2:使用map() + count() + lambda

与上述方法类似,唯一的区别是 map() 用于获取使用 lambda 扩展到整个列表元素的函数。

蟒蛇3

# Python3 code to demonstrate working of
# Mark duplicate elements
# Using map() + count() + lambda
  
# initializing list
test_list = ["gfg", "is", "best", "gfg", 
             "best", "for", "all", "gfg"]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting count till current using count() and slicing
res = list(map(lambda ele: ele[1] + str(test_list[ : ele[0]].count(ele[1]) + 1) if test_list.count(ele[1]) > 1 else ele[1],
               enumerate(test_list)))
  
# printing result
print("Duplicates marked List : " + str(res))

输出: