我可以澄清什么是"data structure that is a list of lists"吗?



>"构建一个数据结构,该结构将是一个列表列表。结构中的列表将包含一个字母字符,然后占位符表示该字母用作单词中第一个字母的次数、用作单词中最后一个字母的次数以及这两个值的总和。

鉴于这一指示,我对预期的情况感到非常困惑。占位符只是另一个空列表吗?例如,代码将如下所示:

listOfLists = [[],[],[],[]]

list[0]将是字母字符list[1]是它用作第一个字母的次数list[2]是它用作最后一个字母的次数list[3]将是两个值的总和

这就是我的设想,但对我来说似乎过于复杂。有人可以为初学者简化它吗?谢谢。

另外,如果用 0 初始化,我们可以只用line[1] += 1递增数字吗?

编辑:感谢教授,我的措辞很糟糕,但有人在下面解释了我的意思,谢谢

我认为您的理解是正确的,结构将是:

list_of_lists = [['a', 0, 0, 0], ['b', 0, 0, 0], ...]

包含字母及其统计信息的列表列表,例如,它作为第一个或最后一个字母出现的次数。

如果一个值已经设置为0,您可以递增该值。

希望这有所帮助。

我也很难理解报价在说什么,所以更多的上下文会很好。 但是重读了几遍之后,这就是我理解的意思:

# A list of words to work with. It didn't explicitly say that this existed but it seemed to imply it.
words = ["apple", "banana", "quince", "vanilla"]
# Then build the multidimensional list:
list_of_lists = []
for letter in "abdcefghijklmnopqrstuvwxyz":
firsts = len([1 for w in words if w[0] == letter])
# this is equivalent to 
# l = []
# for w in words:
#     if w[0] == letter:
#        l.append(1)
# firsts = len(l)
# Although since the idea was to get it into one line, instead of appending to a list we would take the faster and cheaper rout of incrementing a counter like this:
# firsts = 0
# for w in words:
#     if w[0] == letter:
#        firsts += 1
lasts = len([1 for w in words if w[-1] == letter])
list_of_lists.append([letter, firsts, lasts, firsts + lasts])
# list_of_lists should now be something like this:
[['a', 1, 2, 3], ['b', 1, 0, 1] , ['c', 0, 0, 0]] # etc

当然,我可能完全错了,但这是我的看法。 还有一件事。与其做w[0] == letterw[-1] == letter我认为你可以做w.startswith(letter)w.endswith(letter).只有一个字母没有太大区别,但如果您检查多个字母的字符串,它肯定会更容易。 例如,startswith()对于搜索栏特别有用。

最新更新