python里的for in循环如何写

51次阅读
没有评论

共计 511 个字符,预计需要花费 2 分钟才能阅读完成。

在 Python 中,使用 for-in 循环的基本语法是:

for 变量 in 可迭代对象:
    # 循环体代码

其中,可迭代对象 是一个序列(如列表、元组、字符串)或者一个可迭代的对象(如字典、集合),变量 是每次循环时取出的值。

以下是几个 for-in 循环的示例:

  1. 遍历列表:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  1. 遍历字符串:
text = "Hello"
for letter in text:
    print(letter)
  1. 遍历字典的键:
person = {"name": "Alice", "age": 25}
for key in person:
    print(key)
  1. 遍历字典的值:
person = {"name": "Alice", "age": 25}
for value in person.values():
    print(value)
  1. 遍历字典的键值对:
person = {"name": "Alice", "age": 25}
for key, value in person.items():
    print(key, value)

希望这些示例能帮助你理解如何在 Python 中使用 for-in 循环。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-05发表,共计511字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)