如果列表尚未包含所述字符串,则将字符串添加到嵌套的字符串列表

Adding strings to nested lists of strings if list doesn't already contain said string

抱歉这个笨拙的标题。我正在努力学习 Python,我想我会同时整理我的《天际》书 collections。 (有关一般描述,请参见下一段)。我有三个书架,一个在 Whiterun,一个在 Markarth,一个在 Lakeview Manor。我正在尝试制作一个函数,它接受一本书的名称,搜索一个列表(包含 3 个字符串和 3 个其他列表),如果这本书已经在我的图书馆之一,给我一条消息说我已经有那本书。如果这本书不在其中一个图书馆中,请将其添加到适当的嵌套列表中。

我有一个包含字符串和嵌套字符串列表的列表,我想将一个字符串添加到嵌套字符串列表中,但前提是该字符串不在其中一个嵌套列表中。

 library = [ 'Whiterun', ['Book of Riddles', 'Dragonborn'], 'Markarth', ['Dwemer History'], 'Lakeview', ['Nightingales', 'Werewolves'] ]

在图书馆中搜索给定图书的最佳方式是什么?

非常简短和粗略的草图,这看起来像一个字典:

library = {}
library['Whiterun'] = ['Book of Riddles', 'Dragonborn']
library['Markarth'] = ['Dwemer History']
library['Lakeview'] = ['Nightingales', 'Werewolves']

def add_book_to_lib(library, case, book):
  if case in library:
    if book in library[case]:
      print('{0} already exists in {1}'.format(book,case))
    else:
      library[case].append(book)
      print('Added book {0}'.format(book))

  else:
    library[case] = [book]
    print('Created new case {0}'.format(case))

add_book_to_lib(library, 'Whiterun', 'Dragonborn')

如果顺序不是问题,请使用带有集合的字典作为保存书名的值:

 library = {'Whiterun':{'Book of Riddles', 'Dragonborn'}, 
           'Markarth': {'Dwemer History'}, 
           'Lakeview': {'Nightingales', 'Werewolves'} }

然后进行查找,如果您已经添加了这本书或将这本书添加到该部分,则返回一条消息:

def add_book(section, book, lib):
    if book in lib[section]:
        return "Already added {}".format(book)
    library[section].add(book)

您还希望处理该部分可能不存在的情况,并在查找失败时给出适当的消息:

def lookup(section, book, lib):
    try:
        if book in lib[section]:
            return "Already added"
    except KeyError:
        return "Invalid section {}".format(section)
    library[section].add(book)

我想出了一个变通解决方案,它比我最初的想法要简单一些,但可以完成我想要的工作。它将书籍存储在 3 个单独的列表中,因此使用 pickle 将 3 个单独的文本文件用于文件序列化。尽管它不遵循 python 命名约定,因为我要输入大约 400 个函数签名,所以为了方便起见,我只使用了所有大写字母。

'''
Program to track what books I have in my libraries in 3 seperate houses in
skyrim: Whiterun, Markarth, Lakeview Manor
Uses 3 seperate lists for the 3 diff houses.
'''

import pickle

WHITERUN = []
MARKARTH = []
LAKEVIEW = []



def print_lib(library):
     for each_book in library:
          print(each_book)


def have_book(book):
     if WHITERUN.count(book) > 0:
          print('The book: ' + book + ' is already in Whiterun')
          return True
     elif MARKARTH.count(book) > 0:
          print('The book: ' + book + ' is already in Markarth')
          return True
     elif LAKEVIEW.count(book) > 0:
          print('The book: ' + book + ' is already in Lakeview')
          return True
     else:
          return False


def addbook(book, house):
     if not have_book(book):
          house.append(book)
          house.sort()



try:
     with open('whiterun.txt', 'rb') as whiterun_lib:
          WHITERUN = pickle.load(whiterun_lib)
     with open('markarth.txt', 'rb') as markarth_lib:
          MARKARTH = pickle.load(markarth_lib)
     with open('lakeview.txt', 'rb') as lakeview_lib:
          LAKEVIEW = pickle.load(lakeview_lib)
except IOError as err:
     print('File Error: ' +str(err))
except pickle.PicklingError as perr:
     print('Pickling error: ' + str(perr))

print(WHITERUN)
print(MARKARTH)
print(LAKEVIEW)


# whiterun books
addbook('DRAGONBORN', WHITERUN)


# markarth books
addbook('CATS OF SKYRIM', MARKARTH)

#lakeview books
addbook('A DREAM OF SOVNGARDE', LAKEVIEW)

print(WHITERUN)
print(MARKARTH)
print(LAKEVIEW)


try:
     with open('whiterun.txt', 'wb') as whiterun_lib:
          pickle.dump(WHITERUN, whiterun_lib)
     with open('markarth.txt', 'wb') as markarth_lib:
          pickle.dump(MARKARTH, markarth_lib)
     with open('lakeview.txt', 'wb') as lakeview_lib:
          pickle.dump(LAKEVIEW, lakeview_lib)
except IOError as err:
     print('File Error: ' +str(err))
except pickle.PicklingError as perr:
     print('Pickling error: ' + str(perr))