如何从列表中添加/删除项目

时间:2016-08-25 03:32:48

标签: python list

我看到很多帖子在列表中添加和减去字符串,但我需要帮助来保留这些项目的数量。

我想结合这些物品,所以没有重复只是一个柜台。

例: 3苹果4橘子2香蕉

我希望能够"采取"一次一项,如果我打电话: "采取Apple" 然后我要检查我的库存,我会: 2苹果4橘子2香蕉

我也想做相反的事情。我想" drop"一件商品,并将其添加到房间的库存中。

现在我只知道如何一次拿起所有苹果,而不是一次只拿一个苹果。此外,我的项目从一个单独的txt文件加载到程序中,该文件是每个房间的所有项目都保存的地方。

1 个答案:

答案 0 :(得分:0)

考虑使用dictionary代替list。词典非常适合维护counts的{​​{1}}:

things

<强> rooms.txt

from random import choice

def get_rooms(file_name):
    rooms = {}
    with open(file_name) as f:
        for l in f:
            room = l.split()
            room_number = int(room[0])
            rooms[room_number] = {} 
            for index, data in enumerate(room[1:], 1):
                if index % 2:
                    item = data
                else:
                    rooms[room_number][item] = int(data)
    return rooms

def generate_tests(number_of_test_actions):
    tests = []
    for _ in range(number_of_test_actions):
        tests.append((choice([1,2,3,4,5,6]),
                      choice(['Apple', 'Sword', 'Bow', 'Arrow', 'monkey']),
                      choice(['take', 'drop'])))
    return tests

def take_item(room, item):
    # generates and propagates KeyError exception if item not in room
    room[item] -= 1
    if not room[item]:
        room.pop(item)

def drop_item(room, item):
    if item in room:
        room[item] += 1
    else:
        room[item] = 1

rooms = get_rooms("rooms.txt")
for room, item, action in generate_tests(10):
    if action == 'take':
        print('taking', item, 'from room', room, ':', rooms[room])
        try:
            take_item(rooms[room], item)
        except KeyError:
            print('-- Sorry, no', item, 'in room', room, 'to take')
        else:
            print('-- took', item, 'from room', room, ':', rooms[room])                
    elif action == 'drop':
        print('dropping', item, 'in room', room, ':', rooms[room])
        drop_item(rooms[room], item)
        print('-- dropped', item, 'in room', room, ':', rooms[room])

<强>输出

1 Sword 1 Apple 2
2 Apple 3
3 Bow 1 Arrow 3
4 Arrow 5
5 Bow 1
6 Arrow 10