Python 如何防止按主题名称将重复项添加到列表中?你如何通过名字在列表中找到一个项目?
如何防止按主题名称将重复项添加到列表中?你如何通过名字在一封信中找到一个项目Python 如何防止按主题名称将重复项添加到列表中?你如何通过名字在列表中找到一个项目?,python,list,Python,List,如何防止按主题名称将重复项添加到列表中?你如何通过名字在一封信中找到一个项目 shopping_list = [] product = (name, price , quantity, shop_name) if name not in product: shopping_list.append(product) 下面是一个示例,用于检查您的购物清单中是否已经有商品。此项的修改版本可用于按名称查找项。我建议为每个购物项目添加一个唯一的ID,因为名称可能会重叠 def checkIn
shopping_list = []
product = (name, price , quantity, shop_name)
if name not in product:
shopping_list.append(product)
下面是一个示例,用于检查您的购物清单中是否已经有商品。此项的修改版本可用于按名称查找项。我建议为每个购物项目添加一个唯一的ID,因为名称可能会重叠
def checkInShoppingList(shopping_list, product):
in_list = False
for item in shopping_list:
print(item)
if item[0] == product[0]: #Checks each item in list and see if name is a match
print('Item is in list')
in_list = True
break #So it won't iterate through rest of shopping list
if not in_list:
shopping_list.append(product) #Add item to list
return shopping_list
shopping_list = [('item1','3.50', '2', 'shop1')]
product = ('item2', '3' , '1', 'shop1')
shopping_list = checkInShoppingList(shopping_list, product)
product = ('item2', '3' , '1', 'shop1')
newList = checkInShoppingList(shopping_list, product) #Test to add same item again
print('New Shopping list:', newList)
我还建议将数组中的每个产品制作成一本词典请共享一个主题名称是什么?你提到的项目是什么?您可能需要查看。您在哪里设置“name”的值?此外,产品变量永远不会更改,因此将始终触发if。你为什么不在这里使用字典呢?你说的是什么字母?在字母中查找项目?按名称在列表中查找项目,而不是字母。我为问题中的错误道歉。我是python的初学者,在我看来,没有必要使用字典。格式良好的答案,但你最好将购物清单放在dict中,而不是每次想查看时都扫描整个清单以查看是否有产品。