gpt4 book ai didi

Python 3 : How to search for a list created from a user's input?

转载 作者:行者123 更新时间:2023-12-01 08:58:14 25 4
gpt4 key购买 nike

我正在尝试为库存创建列表字典。示例我添加 'fruits'、'vegetables'、'drinks' 作为字典的键,然后为每个元素创建一个列表。创建后,我为每个列表添加两个项目(例如“apple”、“manggo”),以便我可以像这样打印它们:

fruits is list
items in fruits are apple, manggo
veggies is list
items in veggies are cabbage, cucumber
drinks is list
items in drinks are iced tea, juice

但是我无法识别新创建的列表中的项目,我只得到这个:

fruits is list
items in fruits are fruits

我的代码:

class Inventory:


def __init__(self):

self.dict_inv = dict()
self.count_inv = int(input("Enter the number of inventories: "))


for count in range(self.count_inv):

self.name_inv = str(input("Enter Inventory #%d: " % (count+1)))
self.dict_inv[self.name_inv] = count
self.name_inv = list()

sample_add = str(input("Add item here: "))
self.name_inv.append(sample_add)

sample_add2 = str(input("Add another item here: "))
self.name_inv.append(sample_add2)


for keys in self.dict_inv.keys():
if type([keys]) is list:
print("%s is list" % keys)
print("items in %s are %s" % (keys,str(keys)))


Inventory()

最佳答案

您应该测试您的实际列表,而不是从字典中获得的keys() View 列表:

class Inventory:


def __init__(self):

self.dict_inv = dict()
self.count_inv = int(input("Enter the number of inventories: "))


for count in range(self.count_inv):

name_inv = str(input("Enter Inventory #%d: " % (count+1)))

# simply add the list here
self.dict_inv[name_inv] = []

sample_add = str(input("Add item here: "))
# simply add empty list for that key directly, no need to store count here
self.dict_inv[name_inv].append(sample_add)

sample_add2 = str(input("Add another item here: "))
# simply append to the list here
self.dict_inv[name_inv].append(sample_add2)

for key in self.dict_inv.keys():

# dont create a list of one single key, use the dicts value instead
if type(self.dict_inv[key]) is list:
print("{} is list".format(key) )
print("items in {} are {}".format(key, self.dict_inv[key]))


Inventory()

2,egg,1,2,tomato,3,4输入的输出:

egg is list
items in egg are ['1', '2']
tomato is list
items in tomato are ['3', '4']

使用以下命令更改输出:

print("items in {} are {}".format(key, ', '.join(self.dict_inv[key])))

为了更接近您想要的输出:

egg is list
items in egg are 1, 2
tomato is list
items in tomato are 3, 4

HTH

关于Python 3 : How to search for a list created from a user's input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52649867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com