我正在尝试创建清单清单字典。示例我将'fruits', 'vegetables', 'drinks'
添加为字典的键,然后为每个键创建一个列表。创建完成后,我为每个列表添加两个项目(e.g. '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()
答案 0 :(得分:1)
您应该测试您的实际列表,而不是从dict获得的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
答案 1 :(得分:0)
在最后一行中,实际上是在同一处打印两次。首先,您要打印密钥,然后将其转换为字符串并打印。
将最后一行更改为以下内容:
C:\wamp64\bin\php\php5.6.38
这里for key in self.dict_inv.keys():
if type(self.dict_inv[key]) is list:
print("%s is list" % key)
print("items in %s are %s" % (key, *self.dict_inv[key])))
正在访问列表,而前面的self.dict_inv[key]
则将其暴露给列表中的每个项目,而不仅仅是列表本身!
旁注:我认为现在在python 3+中首选使用*
而不是.format()
,但这是重点。