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,則該值將新增到元素的數量中。

  • 否則,對其進行列舉。

  • 這已分配給變數。

  • 這是顯示在控制檯上的輸出。

更新日期: 2021 年 9 月 15 日

145 個瀏覽次數

開啟您的 職業

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.