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.