Python和Java之间的For循环差异
在Python中,我们对循环执行如下操作:Python和Java之间的For循环差异,java,python-3.x,Java,Python 3.x,在Python中,我们对循环执行如下操作: for i in range(len(nums)) 在java中: 我们有: for(int i=0;i
for i in range(len(nums))
在java中:
我们有:
for(int i=0;i
这两个for循环相同吗?如果我们在for循环中做了一些更改,比如说在for循环中,我已经加上了3,对于Java,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;
}
}
nums=[1,3,2,2,5,2,3,7]
公共类解决方案{
公共整数findLHS(整数[]nums){
数组。排序(nums);
int prev_count=1,res=0;
对于(int i=0;i0&&nums[i]-nums[i-1]==1){
而(i
我转换成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)
nums=[1,3,2,2,5,2,3,7]
nums=已排序(nums)
上一次计数=1
res=0
i=0
对于范围内的i(len(nums)-1):
计数=1
如果i>0且nums[i]-nums[i-1]==1:
而i0和nums[i]-nums[i-1]==1:
虽然i这在python中不起作用,i
每次返回到for i in....:代码>
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]
在java中,for循环语义是从C中借用来的
for (<initilization>; <termination condition>; <what to do in after each iteration>)
这里i
接受some\u iterable
中的每个值,循环针对i
的每个值运行一次。如果在循环体中更改i
,则无所谓<代码>i
在下一次迭代中从iterable中分配下一个值。循环的状态保持在iterable中,而不是i
<代码>i
正是允许您访问iterable的当前值的工具。Python for循环本质上与Java的增强for循环相同。对于您的示例,由于范围(len(nums))
返回[0,1,2,…]
,这两个值或多或少是等效的:
Python:
array = [0, 1, 2, 3, 4, 5, 6]
for i in array:
// i represents each item in the array
爪哇:
[3, 2, 2, 2, 3]
for (<initilization>; <termination condition>; <what to do in after each iteration>)
for i in some_iterable:
array = [0, 1, 2, 3, 4, 5, 6]
for i in array:
// i represents each item in the array
int[] array = {0, 1, 2, 3, 4, 5, 6};
for (int i : array) {
// i represents each item in the array
}