Python 的 迭代器循环

等级 3124 次按键

这无限循环列表并获取前7个元素。

Python 代码

# cycle() 无限重复一个可迭代对象;islice() 从迭代器中截取有限部分
1from itertools import cycle, islice
2
# 无限迭代器:red、green、blue、red、green……
3colors = cycle(["red", "green", "blue"])
# islice(colors, 7) 取 7 个后停止;单独 list(colors) 永远不会结束
4result = list(islice(colors, 7))
# 打印 ['red', 'green', 'blue', 'red', 'green', 'blue', 'red']
5print(result)

运行结果

['red', 'green', 'blue', 'red', 'green', 'blue', 'red']
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • "× 6
  • ,× 4
  • (× 4
  • )× 4
  • =× 2
  • [× 1
  • ]× 1

Python 等级 3 的更多代码示例

← 返回 Python 打字练习