当前位置: 首页 > news >正文

不同开发语言之for循环的用法、区别总结

一、Objective-C

(1)标准的c风格

for (int i = 0; i < 5; i++) {
    NSLog(@"i = %d", i);
}

(2)for in循环。

NSArray *array = @[@"apple", @"banana", @"orange"];
for (NSString *fruit in array) {
    NSLog(@"%@", fruit);
}

//这个遍历输出的是值,而不是健

(3)基于块的枚举(Block-Based Enumeration)

Objective-C 提供了基于块的枚举方法,例如 enumerateObjectsUsingBlock:,可以遍历集合类并执行块中的代码。

NSArray *array = @[@"apple", @"banana", @"orange"];
[array enumerateObjectsUsingBlock:^(NSString *fruit, NSUInteger idx, BOOL *stop) {
    NSLog(@"%@ at index %lu", fruit, (unsigned long)idx);
}];

apple at index 0
banana at index 1
orange at index 2

这个类似于python中的for index,item in enumerate(strkk):,可以得到索引值以及内容(值),而且可以通过设置stop值==yes来终止循环

(4)while循环

int i = 0;
while(i<5){
    NSlog(@"%d",i)
    i++;
}
//输出:0 1 2 3 4 

(5)do...while循环

int i= 0 
do{

   NSLog(@"%d",i)
   // 0 1 2 3 4 
   i++

}while(i<5)

二、Python

(1)range()函数

      for   in range(起始, 结束, 步长)

string = "0123456789"
for i in range(0,len(string),2):
    print(f'输出的数据i==={i}')

#输出的数据i===0
#输出的数据i===2
#输出的数据i===4
#输出的数据i===6
#输出的数据i===8

注意range后面的参数,启始、结束、步长,写一个参数代表结束位置,不包括结束位置

对比 Objective-C:

  • 类似于 Objective-C 的标准 for 循环(for (int i = 0; i < 5; i++))。

  • Python 的 range() 更简洁,不需要手动管理循环变量。

(2)for in循环

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

对比 Objective-C:

  • Objective-C 的快速枚举(for...in)与 Python 的 for 循环非常相似。

  • Python 的 for 循环更简洁,不需要指定类型。

(3)enumerate() 函数,也是for in的一种,类似

enumerate() 函数用于在遍历时同时获取索引和值。

fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: orange

对比 Objective-C:

  • 类似于 Objective-C 的基于块的枚举(enumerateObjectsUsingBlock:)。

  • Python 的 enumerate() 更简洁,不需要额外的语法。

(4)while循环

i = 0
while i < 5:
    print(f"i = {i}")
    i += 1

对比 Objective-C:

  • 与 Objective-C 的 while 循环几乎一致。

  • Python 不需要分号或大括号,使用缩进来定义代码块。

Python 的设计哲学强调简洁性和可读性。do...while 循环的使用场景相对较少,而且可以通过 while True 和 break 轻松模拟,因此 Python 没有专门引入 do...while 语法。

(5)列表推导式(就是for in循环中写表达式)

列表推导式是一种简洁的创建列表的方式,可以替代简单的 for 循环。

[表达式 for 变量 in 可迭代对象]

squares = [x ** 2 for x in range(5)]
print(squares)

#[0, 1, 4, 9, 16]
  • 先看for in range函数,输出的x在加上前面的表达式,然后最终生成值输出

  • Python 的列表推导式非常简洁,适合快速生成列表。

(6)zip() 函数

zip() 函数用于同时遍历多个可迭代对象。

for 变量1, 变量2 in zip(可迭代对象1, 可迭代对象2):
    # 循环体

fruits = ["apple", "banana", "orange"]
prices = [1.0, 0.5, 0.8]
for fruit, price in zip(fruits, prices):
    print(f"Fruit: {fruit}, Price: {price}")

#Fruit: apple, Price: 1.0
#Fruit: banana, Price: 0.5
#Fruit: orange, Price: 0.8

这个其实没有特殊的,就是通过for in 同时遍历多个对象

三、Swift

swift中先明白什么是区间运算符

  • 闭区间运算符(n…m),n 不能大于 m,相当于数学的 [n, m]

  • 半开区间运算符(n…<m),相当于数学的 [n, m)

(1)for in 区间

//开区间,输出12到30包括12和30
 for index in 12...30{
    print("index==\(index)")
 }
//半开区间,输出12到29,不包括30
 for index in 12..<30{
    print("index==\(index)")
 }

    (2)stride 函数(其实类似python中的for in range)

            for 变量 in stride(from: 起始值, to: 结束值, by: 步长) {
                // 循环体
            }
            for index in stride(from: 0, to: 20, by: 3){
                print("输出index==\(index)")
            }
            /*
             输出index==0
             输出index==3
             输出index==6
             输出index==9
             输出index==12
             输出index==15
             输出index==18
             */
    •  swift中的这for in 加区间运算以及 for in stride函数类似python的for in range 函数,

    • 第一个函数swift使用范围运算符(..< 或 ...),stride函数类似python使用range(启始、结束、步长),

    (3)for-in 循环

    let fruits = ["apple", "banana", "orange"]
    for fruit in fruits {
        print(fruit)
    }
    #输出apple banana orange
    • Swift 的 for-in 跟python、oc中的差不多,都是输出内容值,不是索引

    (4)enumerated循环

    let fruits = ["apple", "banana", "orange"]
    for (index, fruit) in fruits.enumerated() {
        print("Index: \(index), Fruit: \(fruit)")
    }
    • 类似于 Objective-C 的基于块的枚举(enumerateObjectsUsingBlock:)。

    • 类似于python中的enumerate

    for k,v in enumerate(strkk):
        print(f'k=={k},v={v}')

    (5)while循环

     var i = 0
     while (i < 5) {
        print("i==\(i)")
        i += 1
     }

    while函数也跟python、oc差不多,只是这里注意swift的语法,

    • Swift 不需要分号或括号,使用缩进来定义代码块

    • 运算符之间需要有空格

    • 不能使用oc中的i++,需要写成 i += 1

    (6)repeat-while循环

    var i = 0
    repeat {
        print("i = \(i)")
        i += 1
    } while i < 5

    • 类似于 Objective-C 的 do...while 循环:

    int i = 0;
    do {
        NSLog(@"i = %d", i);
        i++;
    } while (i < 5);
    • Swift 的 repeat-while 更简洁。

    (7)forEach 方法

    let fruits = ["apple", "banana", "orange"]
    fruits.forEach { fruit in
        print(fruit)
    }
    

    注意swift中forEach的写法,注意区别与js的写法

    四、Kotlin

    (1)类似swift的tride函数

    kotlin中也有区间运算符..跟swift you区别

    1、闭区间运算swift是...,但是kotlin是..和一个是三个点一个是两个点

    2、半封闭区间,swift是..<,kotlin用until 表示左闭右开区间

    //这个类似swift的...闭空间,输出内容包括4
    for (i in 0..4) {
        println("i = $i")
    }
    
    //下面这个是until表示半封闭空间,不包括10 ,加了步长step
    for (i in 0 until 10 step 2) {
        println("i = $i")
    }
    

    对比 Swift:

    • 类似于 Swift 的 stride 函数:

      for i in stride(from: 0, to: 10, by: 2) {
          print("i = \(i)")
      }

    (2)for-in 循环

    val fruits = listOf("apple", "banana", "orange")
    for (fruit in fruits) {
        println(fruit)
    }

    对比 Swift:

    • 类似于 Swift 的 for-in 循环。

    • Kotlin 的 for 循环更简洁,不需要指定类型。

    (3)withIndex 方法(类似swift的enumerated循环)

    val fruits = listOf("apple", "banana", "orange")
    for ((index, fruit) in fruits.withIndex()) {
        println("Index: $index, Fruit: $fruit")
    }

    对比 Swift:

    • 类似于 Swift 的 enumerated 方法:

    for (index, fruit) in fruits.enumerated() {
        print("Index: \(index), Fruit: \(fruit)")
    }
    • Kotlin 的 withIndex 语法更简洁。

    (4)while循环、do-while 循环

    while循环、do-while 循环kotlin跟swift以及oc都差不多,只是swift没有do-while 循环,而是叫做repeat-while,效果都一样

    var i = 0
    while (i < 5) {
        println("i = $i")
        i++
    }
    
    var i = 0
    do {
        println("i = $i")
        i++
    } while (i < 5)

    Kotlin 的集合类提供了 forEach 方法,用于遍历集合中的每个元素。

    (4)forEach 方法

    val fruits = listOf("apple", "banana", "orange")
    fruits.forEach { fruit ->
        println(fruit)
    }

    对比 Swift:

    • 类似于 Swift 的 forEach 方法:

    fruits.forEach { fruit in
        print(fruit)
    }

    五、Js

    (1)标准的c风格

    for (let i = 0; i < 5; i++) {
        console.log(`i = ${i}`);
    }

    (2)for...in 循环

    for...in 循环会遍历对象的所有可枚举属性(包括原型链上的属性),对于字符串,for...in 会遍历字符串的索引(键),而不是直接遍历字符。

    (3)for...of 循环

            //这里遍历的是索引
            for (const index in string) {
                console.log(`输出的内容${index}`)
            }
            //for of遍历的是内容值
            for (const element of string) {
                console.log(`输出的内容${element}`)
            }       

    js中for in循环出来的是索引,想要得到内容值需要for of,但是这里要注意,虽然 for...in 可以用于数组或字符串,但它会遍历所有可枚举属性,包括原型链上的属性,可能会导致意外行为。对于数组或字符串,更推荐使用 forfor...of 或 forEach 等方法,比如:

    // 给字符串的原型添加一个属性
    String.prototype.customProp = "test";
    
    const str = "hello";
    for (const index in str) {
      console.log(`Index: ${index}, Character: ${str[index]}`);
    }
    
    Index: 0, Character: h
    Index: 1, Character: e
    Index: 2, Character: l
    Index: 3, Character: l
    Index: 4, Character: o
    Index: customProp, Character: t

    我们看到它不止是遍历出了hello还遍历出了customProp属性

    (4)while循环、do-while 循环

    while循环、do-while 循环kotlin跟swift以及oc都差不多,只是swift没有do-while 循环,而是叫做repeat-while,效果都一样

    (5)forEach 方法

    const fruits = ["apple", "banana", "orange"];
    fruits.forEach((fruit) => {
        console.log(fruit);
    });

    (6)map 方法(针对数组)

    const 新数组 = 数组.map((变量) => {
        // 返回新值
    });
    const numbers = [1, 2, 3];
    const squares = numbers.map((num) => num * num);
    console.log(squares);

    对比 Swift:

    • Swift 的 map 方法:JavaScript 的 map 与 Swift 的 map 非常相似。

      let numbers = [1, 2, 3]
      let squares = numbers.map { $0 * $0 }
      print(squares)
    • 对比python,其实也很像python中的列表推到式

      squares = [i ** 2 for i in range(1,4,1)]
      print(f'打印出squares=={squares}') 

    相关文章:

  • nginx 代理 redis
  • 【目标检测】【NeuralPS 2023】Gold-YOLO:通过收集与分发机制实现的高效目标检测器
  • nginx-静态资源部署
  • 如何在WPS中接入DeepSeek并使用OfficeAI助手(超细!成功版本)
  • WordPress报502错误问题解决-php-fpm-84.service loaded failed failed LSB: starts php-fpm
  • 天锐蓝盾数据防泄露系统 | 企业内部终端管理
  • docker1
  • [通俗易懂C++]:std::optional
  • Docker Compose企业示例
  • Windows11下玩转 Docker
  • 计算机毕业设计SpringBoot+Vue.js网络海鲜市场系统(源码+文档+PPT+讲解)
  • 理解 UDP 协议与实战:Android 使用 UDP 发送和接收消息
  • MQTT协议下温度数据上报观测云最佳实践
  • 架构师面试(十一):消息收发
  • 重邮数字信号处理-实验三z 变换及离散 LTI 系统的 z 域分析
  • Linux之网络管理配置(Network Configuration Management in Linux)
  • 可视化+图解:轻松搞定链表
  • OpenIndiana Hipster系统安装配置
  • MyBatis-Plus 与 Spring Boot 的最佳实践
  • 实现NTLM relay攻击工具的Python代码示例
  • 北京网站制作建设公司/大型网站制作
  • 大连金州/太原建站seo
  • 义乌缔造网络科技有限公司/seo关键词排名技术
  • 用asp做的一个网站实例源代码/搜索引擎优化网站排名
  • 什么公司做网站最好/外贸是做什么的
  • 巢湖网站建设/免费网页在线客服系统代码