代码之家  ›  专栏  ›  技术社区  ›  S A

Python简单循环问题

  •  0
  • S A  · 技术社区  · 8 年前

    目前正在学习python。通常是C++人员。

    if wallpaper == "Y":
        charge = (70)
        print ("You would be charged £70")
        wallpaperList.append(charge)
    
    elif wallpaper == "N" :
        charge = (0)
    
    else:
        wallPaper ()
    
    surfaceArea
        totalPapers = 0
        for item in range (len(wallpaperList)):
            totalPapers += wallpaperList[item]
    

    我正在尝试为if语句执行for循环。

    在c++中,这将是一个简单的

    for (I=0; i<pRooms; i++){
    }
    

    我试图在for循环中添加上述代码,但似乎失败了。

    谢谢

    2 回复  |  直到 8 年前
        1
  •  4
  •   erip Jigar Trivedi    8 年前

    Python循环遍历iterable中的所有内容:

    for item in wallpaperList:
            totalPapers += item
    

    在现代C++中,这类似于:

    std::vector<unsigned int> wallpaperList;
    
    // ...
    
    for(auto item: wallpaperList) {
        totalPapers += item
    }
    

    您也可以使用 sum 功能:

    cost = sum(wallpaperList)
    

    如果费用是 70 每次,为什么不只是做乘法呢?

    while wallPaper == 'Y':
        # ...
    
        # Another satisfied customer!
        i += 1
    
    cost = i * 70
    
        2
  •  2
  •   alexis    8 年前

    对于您的 for 循环,使用 range :

    for (i=0; i<pRooms; i++){   # C, C++
    }
    
    for i in range(pRooms):     # Python
        ...
    

    两个循环都迭代这些值 0 pRooms-1 。但python给了你其他选择。您可以在不使用索引的情况下遍历列表的元素:

    for room in listOfRooms:
        if room.wallpaper == "Y":
            ...
    

    列表解析 也很好。如果你不在乎 print 在你的代码中调用,你可以这样计算一行的成本:

    totalPapers = sum(70 for room in listOfRooms if room.wallpaper == "Y")