Python和Java中for循环的区别

3

在Python中,我们使用for循环的方法如下:

for i in range(len(nums))

在Java中,我们有:
for (int i = 0; i < nums.length; i++)

这两个for循环是否相同?如果我们在for循环内部进行了一些更改,比如说对于Java语言,i增加了3,在for循环中,下一个i将会是4吗?而Python仍然从2开始。

Leetcode 594. 最长和谐子序列。

我们定义一个和谐数组是指其最大值和最小值之间的差恰好为1。

以下是Java语言写的解决方案:

nums=[1,3,2,2,5,2,3,7]
public class Solution {
    public int findLHS(int[] nums) {
        Arrays.sort(nums);
        int prev_count = 1, res = 0;
        for (int i = 0; i < nums.length; i++) {
            int count = 1;
            if (i > 0 && nums[i] - nums[i - 1] == 1) {
                while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
                    count++;
                    i++;
                }
                res = Math.max(res, count + prev_count);
                prev_count = count;
            } else {
                while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
                    count++;
                    i++;
                }
                prev_count = count;
            }
        }
        return res;
    }
}

我转向使用Python编程语言:

nums=[1,3,2,2,5,2,3,7]

nums=sorted(nums)
prev_count=1
res=0
i=0
for i in range(len(nums)-1):
    count=1
    if i>0 and nums[i]-nums[i-1]==1:
        while i<len(nums)-1 and nums[i] == nums[i+1]:
            count+=1
            i+=1
        res=max(res,count+prev_count)
        prev_count=count
    else:
        while i<len(nums)-1 and nums[i] == nums[i+1]:
            count+=1
            i+=1

        prev_count=count

print (res)


在Java中

for (int i = 0; i < nums.length; i++) {
            int count = 1;
            if (i > 0 && nums[i] - nums[i - 1] == 1) {
                while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
                    count++;
                    i++;
                }

在for循环中使用i++,因此i从添加了的值开始。

在Python中:


代码示例不明确,请提供更多上下文信息,以便进行正确的翻译。
for i in range(len(nums)-1):
    count=1
    if i>0 and nums[i]-nums[i-1]==1:
        while i<len(nums)-1 and nums[i] == nums[i+1]:
            count+=1
            i+=1

在 i+=1 之后,它仅适用于 While 循环,而对于循环则仍从 i=2 而不是 4 开始。Java 返回的答案是 5,而 Python 的答案是 4。我调试了代码,看起来 Java 会使用已添加的 i 进行计算,而 Python 则不使用添加的 i,并且总是从最后一个 i 开始。
3个回答

2

Java的for循环语义是从C中借鉴过来的。

for (<initilization>; <termination condition>; <what to do in after each iteration>)

在开始(初始化)时做一些事情,之后直到达到某个条件(终止条件),做一些事情以推进进程(每次迭代后要做什么)。使用带有i的成语化for循环可以工作,因为i中的迭代状态被维护。 因此,如果在循环体中对i进行更改,则迭代的状态也会更改。
Python语法类似于bash循环:
for i in some_iterable:

在这里,i 依次取 some_iterable 中的每个值,并且循环每次运行都会执行一次。如果你在循环体内改变了 i,那没关系;在下一次迭代期间,i 将被分配下一个可迭代对象中的值。循环状态保存在可迭代对象中,而不是 ii 只是让你访问可迭代对象的当前值。"最初的回答"

2

Python的for循环和Java的增强型for循环基本上是相同的。对于你的例子来说,因为range(len(nums))返回[0, 1, 2, ...],这两种方式更或多或少是等价的:

Python:

最初的回答:Python的for循环和Java的增强型for循环基本相同。对于这个例子,因为`range(len(nums))`返回`[0, 1, 2, ...]`,因此这两者基本等效。
    array = [0, 1, 2, 3, 4, 5, 6]
    for i in array:
        // i represents each item in the array

Java:

    int[] array = {0, 1, 2, 3, 4, 5, 6};
    for (int i : array) {
        // i represents each item in the array
    }

1
这在Python中不起作用 - 每次回到“for i in ...:”时,i会被“重置”。
for i in range(20) :
   print(i)    # prints i
   i += 99     # has no influence over the next iterations i
   print(i)    # prints (i + 99) 

一种在Python中解决它的方法是:

from collections import Counter

nums=[1,3,2,2,5,2,3,7]

c = Counter(nums)

# create possible keys from c that are 1 apart
one_apart_keys = [ (a, a+1) for a in c if a+1 in c]     

# get the key that has the max value of counts
# will pick first one if multiple equals possible
max_key = max(one_apart_keys, key = lambda x: c[x[0]]+c[x[1]]) 

# get all the numbers in order from list
collec = [x for x in nums if x in max_key]  

print(collec)

# c is                Counter({2: 3, 3: 2, 1: 1, 5: 1, 7: 1})
# one_apart_keys is   [(1, 2), (2, 3)]
# max_key is          (2, 3)

输出:

[3, 2, 2, 2, 3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接