【问题标题】:Python For Loop Syntax to JavaPython For 循环语法到 Java
【发布时间】:2016-10-12 00:45:31
【问题描述】:
 for j in [c for c in coinValueList if c <= cents]:

你会如何用java编写这个for循环? 是吗

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

我不确定应该将 c 和 j 与什么进行比较。 CoinValueList = {1,5,10,25} cents = 0 -- 在这两个之前它在自己的 for 循环中。

【问题讨论】:

  • 您在上面的 python 代码中迭代列表中的数据,所以下面将是您如何顺序访问列表或数组的数据。
  • 我认为这绝对不是发布的 java 代码。为什么不用英语解释你想要什么逻辑。

标签: java python for-loop syntax


【解决方案1】:

让我们分解:

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
    }
}

【讨论】:

    【解决方案2】:

    如果你想用 Java 翻译成字面意思

    List<Integer> newList = new ArrayList();
    
    for(Integer c : coinValueList) {
        if(c <= cents) {
            newList.append(c);
        }   
    }
    
    for(Integer j : newList) {
        # do something
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-07
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      相关资源
      最近更新 更多