Python 程式 - 標註字串中的重複元素
當需要標註字串中的重複元素時,應使用列表解析和“count”方法。
示例
以下是相同內容的演示:
my_list = ["python", "is", "fun", "python", "is", "fun", "python", "fun"]
print("The list is :")
print(my_list)
my_result = [value + str(my_list[:index].count(value) + 1) if my_list.count(value) > 1 else value for index, value in enumerate(my_list)]
print("The result is :")
print(my_result)輸出
The list is : ['python', 'is', 'fun', 'python', 'is', 'fun', 'python', 'fun'] The result is : ['python1', 'is1', 'fun1', 'python2', 'is2', 'fun2', 'python3', 'fun3']
解釋
定義一個列表並在控制檯上顯示該列表。
列表解析用於迭代值並檢查數量。
如果特定值的數量大於 1,則該值將新增到元素的數量中。
否則,對其進行列舉。
這已分配給變數。
這是顯示在控制檯上的輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP