添加具有货币格式的变量和搜索列表的最佳解决方案



我有以下代码:

完整代码列表:https://repl.it/JSUN/1

出于教学目的,我正在寻找两件事的最佳方法/解决方案:

问题 1.使用货币变量,例如存储在下面购物篮列表中的变量

basket=[['Iphone', '£900'], ['Samsung', '£1020'], ['Toshiba', '£700']]

在结帐子中,目的是将相应物料的成本相加。

因此,如果购物篮包含上述项目,则所需的输出为 900 英镑 + 1020 英镑 + 700 英镑=£2620

我已经尝试了各种方法,例如转换为整数,这显然不起作用,我想某种字符串操作可能是唯一的前进方法(这似乎不必要地复杂(。像 VB.Net 这样的语言具有货币数据类型,这将使此任务变得相当简单。解决这个问题的pythonic方法是什么?

Q2.用于循环遍历整个购物篮以在结账时生成购物篮中的所有商品,而不仅仅是前 2

个我试过这个,但没有用:

for items in basket:
print("Your total bill is:", basket[items][1])
items=items+1

而这个,也是错误的:

for i in len(basket):
print("Your total bill is:", basket[i][1])

错误:

TypeError: 'int' object is not iterable

这两个问题都是相互关联的,因为它们都与 checkout(( 子有关,其中在购物篮列表中添加所有货币变量是目标!

Q1:

鉴于它仅用于基本的教学目的,您可以去掉井号(假设表示一致(:

def extract_cost(money_in_pounds):
return int(money_in_pounds[1:])
basket = [['Iphone', '£900'], ['Samsung', '£1020'], ['Toshiba', '£700']]
total_cost = 0
for items in basket:
total_cost = total_cost + extract_cost(items[1])
print(total_cost)

无需编写其他函数

basket = [['Iphone', '£900'], ['Samsung', '£1020'], ['Toshiba', '£700']]
total_cost = 0
for items in basket:
# items[1] selects the cost
# items[1][1:] selects the sub-string of that cost from the 1st index to the end, i.e. remove the currency notation
# int() then converts it into an integer
cost_in_pounds = int(items[1][1:])
total_cost = total_cost + cost_in_pounds
print(total_cost)

更简洁的代码(由下面的Jon Clements建议(

total_cost = sum(int(cost[1:]) for item_name, cost in basket)

问2:

items不是索引,而是列表的内容,所以项目本身就是内部列表:

for items in basket:
print("Your total bill is:", items[1])

最新更新