Python - 列表中交替元素模式的增加


這個教程中,我們將使用列表推導與 Python 的 enumerate() 函式,Python 提供了一種簡潔的語法,可以從另一個列表中派生出一個列表。這些表示式稱為列表推導。列表推導是 Python 中最強大的工具之一。Python 的列表推導是一個例子,說明了該語言對函數語言程式設計概念的支援。你可以在此處閱讀更多有關它的資訊 "www.tutorialspoint.com/python-list-comprehension" enumerate() 方法將計數器新增到可迭代元素。你可以在此處閱讀有關 enumerate 的更多資訊 " www.tutorialspoint.com/enumerate-in-python"

範例

 動態演示

# declare list of integers
my_list = [1, 2, 3]
# printing the value
print("Printing my_list list : " + str(my_list))
response = [value for sub in ((i, "*" * j)
   for j, i in enumerate(my_list, 1))
   for value in sub]
# print result
print("The increasing element pattern IS : " + str(response))

輸出

Printing my_list list : [1, 2, 3]
The increasing element pattern IS : [1, '*', 2, '**', 3, '***']

更新時間: 2020 年 5 月 16 日

108 次瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.