Python For循环语法到J

2024-09-29 02:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

 for j in [c for c in coinValueList if c <= cents]:

您将如何用java编写这个for loop out? 是吗

for(j=0, j <= cents, j++){
    for(c=0; c<= cents, j++){

我不知道c和j应该和什么比较。 CoinValueList={1,5,10,25} 美分=0——在这两个之前它在自己的for循环中。你知道吗


Tags: inloopforifjavaoutcentscoinvaluelist
2条回答

如果你想用Java翻译的话

List<Integer> newList = new ArrayList();

for(Integer c : coinValueList) {
    if(c <= cents) {
        newList.append(c);
    }   
}

for(Integer j : newList) {
    # do something
}

但通常不需要第二个for循环

让我们分解:

array = [c for c in coinValueList if c <= cents] # produces an array of coins from coinValueList that are <= cents
for j in array: # iterates over array
    #stuff

所以我们只能在一个循环中完成,java等价物是:

for(int j=0; j<coinValueList.length; j++) {
    if(coinValueList[j] <= cents) {
        #stuff
    }
}

相关问题 更多 >