掌握 Python 列表:您需要了解的基本技术
哈喽!大家好,很高兴又见面了,我是的一名作者,今天由我给大家带来一篇《掌握 Python 列表:您需要了解的基本技术》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
这将循环遍历列表,并且列表中的每个元素在每次迭代中都可以作为变量使用。当需要遍历列表中的所有元素时,这被广泛使用。
operating_systems = ["windows", "mac", "linux"] for os in operating_systems: print(os)`
# output windows mac linux
当需要根据索引访问并且需要索引值时。
operating_systems = ["windows", "mac", "linux"] for i in range(len(operating_systems)): print(f"index {i}: {operating_systems[i]}")
# output index 0: windows index 1: mac index 2: linux
如果您同时需要索引和值,这是一种优雅的方式
operating_systems = ["windows", "mac", "linux"] for index, os in enumerate(operating_systems): print(f"index is {index} and value is {os}")
# output index is 0 and value is windows index is 1 and value is mac index is 2 and value is linux
operating_systems = ["windows", "mac", "linux"] i = 0 # inital condition, required to start while i < len(operating_systems): print(f"while looping {i} got the value {operating_systems[i]}") i = i + 1 # this is very important, dont forget about infinite loops
# output while looping 0 got the value windows while looping 1 got the value mac while looping 2 got the value linux
可以很好地控制何时向前移动迭代器,尽管我们必须依靠 stopiteration 来检查是否到达末尾。
operating_systems = ["windows", "mac", "linux"] iterator = iter(operating_systems) while true: try: os = next(iterator) print(f"consumed form iterator {os}") except stopiteration: print("consumed all from iterator") break
# output consumed form iterator windows consumed form iterator mac consumed form iterator linux consumed all from iterator
# hack to avoid stopiteration iterator = iter(operating_systems) end_of_list = object() reached_end = false while not reached_end: os = next(iterator, end_of_list)# a predefined object as end of the list if os != end_of_list: print(os) else: reached_end = true
需要转型时
operating_systems = ["windows", "mac", "linux"] os_uppercase = [os.upper() for os in operating_systems] print(os_uppercase)
# output ['windows', 'mac', 'linux']
当需要循环浏览列表时。使用适当的边界条件来打破循环
import itertools operating_systems = ["windows", "mac", "linux"] for item in itertools.cycle(operating_systems): print(item) # infinite cycling loopmake sure to have proper boundary condition to break
# output windows mac linux windows mac linux windows mac linux windows mac linux windows ....... infinite loop
同时循环多个列表。如果列表大小不同,请注意输出。
operating_systems = ["windows", "mac", "linux"] mobile_operating_systems = ["android", "ios"] for os, mobile_os in zip(operating_systems,mobile_operating_systems): print(os, mobile_os)
# output windows android mac ios
operating_systems = ["windows", "mac", "linux"] for reversed_os in reversed(operating_systems): print(reversed_os)
# Output linux mac windows
今天关于《掌握 Python 列表:您需要了解的基本技术》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除