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

时间:2015-09-05 22:01:47

标签: python string list nested-lists

抱歉笨拙的头衔。我正在尝试学习Python,我想我会同时组织我的Skyrim书籍收藏。 (有关一般说明,请参阅下一段)。我有三个书柜,一个在Whiterun,一个在Markarth,一个在Lakeview庄园。我正在尝试创建一个函数,它接受一本书的名称,搜索一个列表,(包含3个字符串和另外3个列表),如果该书已经在我的一个库中,请给我一条消息说我已经有那本书。如果该书不在其中一个库中,请将其添加到适当的嵌套列表中。

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

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

在库中搜索给定书籍的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

如果订单不是问题,请使用带有集合的dict作为保存书名称的值:

 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)

答案 1 :(得分:1)

非常简短粗略的草图,用dict看起来如何:

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')

答案 2 :(得分:0)

我想出了一个解决方案,它比我原来的想法更简单但是能完成我想要的工作。它将书籍存储在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))