繁体   English   中英

如何对 Python 列表的特定整数值求和

[英]How to sum specific integer values of Python List

我正在尝试使用 sum 函数对列表中的整数值求和。 不幸的是,它添加了列表的所有值,但没有添加用户需要的值。

这是我的代码:

tourist_attractions = []
distance = []
entry_cost = []

for i in range(3):
    tourist_attractions.append (input("Enter Tourist place: "))


    tourist_distance =(int(input("Enter distance: ")))

    if tourist_distance > 50:
        print("Invalid Entry")
        continue

    if tourist_distance <= 50:
        distance.append(tourist_distance)

    cost = (float(input("Enter cost: ")))

    if cost > 100:
        print("cost must be between 1-100")
        continue

    if cost > 0 or cost <= 100:
        entry_cost.append(cost)

print()

for line in tourist_attractions:
    print("Place:", line)

for line in distance:
    print("Distance:", line)

for line in entry_cost:
    print("Cost:", line)


print()

number_of_places_to_visit = int(input("Total number of places to visit: "))

x = 1

while x <= number_of_places_to_visit:

    select_tourist_place = input("select tourist place, 0-3: ")

    x = x + 1


    if select_tourist_place == "0":
        print(tourist_attractions[0], distance[0], entry_cost[0])

    elif select_tourist_place == "1":
        print(tourist_attractions[1], distance[1], entry_cost[1])

    elif select_tourist_place == "2":
        print(tourist_attractions[2], distance[2], entry_cost[2])

    elif select_tourist_place == "3":
        print(tourist_attractions[3], distance[3], entry_cost[3])

    elif select_tourist_place == "4":
        print(tourist_attractions[4], distance[4], entry_cost[4])



print("total cost: " , sum(entry_cost))

结果我得到:

Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20

Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0

Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost:  50.0
>>> 

我可以理解,目前它正在总结所有附加的 entry_cost 列表,并给我总共 50 个,其中应该是来自伦敦的 15 个和来自曼彻斯特的 15 个。 有什么帮助吗?

print("total cost: " , sum(entry_cost))

绝对说明您正在迭代所有入门成本。 您可能想要存储选定的索引并对这些索引的条目求和。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM