Python简单循环问题

2024-05-15 22:55:50 发布

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

目前正在学习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循环中添加上述代码,但似乎失败了。你知道吗

谢谢


Tags: youforifbeitemprintelifwallpaper
2条回答

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

对于for循环的确切等价物,请使用range

for (i=0; i<pRooms; i++){   # C, C++
}

for i in range(pRooms):     # Python
    ...

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

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

列表理解也很好。如果您不关心代码中的print调用,那么您可以使用以下方法计算一行中的开销:

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

相关问题 更多 >