该计划的目标是:
提示用户提供所需物品数量
阅读所需的项目
提示用户购买的商品数量
阅读已购买的商品
最后,比较两个列表,看看哪些商品已被购买,哪些商品已被购买。
即
“以下是您仍需购买的物品: 面包 蛋 蛋 火腿
以下是您购买的不必要物品: 芯片 火鸡“
到目前为止,这是我的代码:
count = 1
count2 = 1
# of items on list
item_numN = int(raw_input("Please enter the number of items on your grocery list.\n"))
for i in range (0,item_numN):
item_list = str(raw_input("What is the item #" + str(count) + " on your list?\n"))
count = count + 1
# of items bought
item_numB = int(raw_input("Please enter the number of items you bought.\n"))
for i in range (0,item_numB):
item_bought = str(raw_input("What is the item #" + str(count2) + " that you bought?\n"))
count2 = count2 + 1
我无法弄清楚如何阅读两组独立的输入并进行比较。任何帮助将不胜感激。
答案 0 :(得分:1)
您可以使用集来查找差异。
尽量保留原始代码:
item_numN = int(raw_input("Please enter the number of items on your grocery list.\n"))
item_list = [str(raw_input("What is the item #" + str(count + 1) + " on your list?\n")) for count in range(item_numN)]
item_numB = int(raw_input("Please enter the number of items you bought.\n"))
item_bought = [str(raw_input("What is the item #" + str(count + 1) + " that you bought?\n")) for count in range(item_numB)]
items_needed = set(item_list) - set(item_bought)
print 'You still need {}.'.format(', '.join(items_needed))
这是一个示例会话:
Please enter the number of items on your grocery list.
3
What is the item #1 on your list?
apples
What is the item #2 on your list?
pears
What is the item #3 on your list?
beer
Please enter the number of items you bought.
4
What is the item #1 that you bought?
beer
What is the item #2 that you bought?
paper
What is the item #3 that you bought?
pencil
What is the item #4 that you bought?
roses
You still need apples, pears.
相比之下,未在列表中购买的商品将是set(item_bought) - set(item_list)
。
答案 1 :(得分:0)
这是作业吗?
你缺少的第一件事是你需要创建空列表然后追加给他们
像
这样的东西item_bought=[]
for i in range (0,item_numB):
item_bought.append(str(raw_input("What is the item #" + str(count2) + " that you bought?\n")))
然后你就可以比较它们的分类和循环。
答案 2 :(得分:0)
Python中的列表和集合没有预设的大小限制,它们可以说无穷无尽。 所以你真的不需要问用户购买了多少件物品。你可以提示这样的事情:
items_bought=[]
items_to_buy=[]
item_count=1
while item != 'Done' or item != 'done':
item = str(raw_input("Add item #%i or type done if you are finished"%item_count))
items_bought.append(item)
item_count+=1
item_count-=1 #due to last iteration, when user decides, that this is it, item count will be by 1 higher
购买清单也可以。注释集每个项目只包含1个实例,列表可以包含许多可重复的项目。 参考有关Python数据sructs的文档:Python Data Structures
更新:要了解可迭代数据结构,这里有一些提示: 您可以像这样调用列表项: LIST_NAME [ITEM_NUMBER] 枚举从0开始,因此列表中的项目将是:list_name [0],list_name 1 ... list_name [n-1],共有n个项目。 切片。您可以在python中对iterables进行切片,如下所示: LIST_NAME [START_POSITION:end_position:步骤]。您也可以从列表末尾切换到开头。这是关于切片的堆栈溢出线程的链接:Slicing in Python
祝你好运,Python是一门很好的学习语言,你一定很喜欢它。