Python 3: Как искать список, созданный из пользовательского ввода? - PullRequest
0 голосов
/ 04 октября 2018

Я пытаюсь создать словарь списков для инвентаря.Пример Я добавляю '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()  

Ответы [ 2 ]

0 голосов
/ 04 октября 2018

В последней строке вы печатаете одно и то же дважды.Сначала вы печатаете ключ, затем преобразуете его в строку и печатаете.

Измените последнюю строку на следующую:

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] обращается кlist и * впереди выставляет его каждому элементу в списке, а не только самому списку!

Примечание: я думаю, что в python 3+ сейчас предпочитают использовать .format() вместо %, но это не относится к делу.

0 голосов
/ 04 октября 2018

Вы должны проверить свои фактические списки, а не список ключей () - представление, которое вы получаете из dict:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...