创建和排序动态列表列表

时间:2018-03-24 17:50:38

标签: python

这是我试图解决的更具挑战性的问题。我知道我可以创建一个空列表sortedList =[[],[],[]]的列表,在这种情况下,索引0处的sortedList有一个空列表,在索引1和2处相同。

我的任务是收集用户的输入并创建单词列表,并在用户输入停止时停止。我做得很好,做得很好:

def wordList():
unsortedList=[]
promptUser=""   
while promptUser !="stop":

    promptUser = input("Type words, one at a time. When you are done, type stop: ")
    unsortedList.append(promptUser)
    if promptUser =="stop":
        unsortedList.pop(-1)


#print(wordList)
wordList()

我不得不使用草率代码来使用pop方法不包含单词stop。不漂亮,但它的工作原理。我真正的问题是这个。我需要一段时间或for循环来遍历unsortedList并查看每个单词并对其进行评估以获得列表中每个项目的计数。

从概念上讲,我没关系,但挑战在于,基于对unsortedList中每个项目的评估,我应该创建一个sortedList,它按照长度分组所有用户输入并为每个长度组创建一个新列表所以根据用户输入动态创建的列表列表,并根据字符数进行分组。

所以我知道列表列表将遵循索引顺序,第一个列表将是索引0,依此类推。我也明白,可以通过unsortedList获取列表中每个项目的字符数。从理论上讲,我可以取所有长度为n的单词并将它们插入子列表,然后找到长度不同的所有单词n并将它们放在子列表中。

高级我的unsortedList将包含可以根据字符长度排序的各种单词。我可以假设任何单词都不会超过10个字符,但空字符串是可能的。

浏览这个unsortedList并创建一个sortedList,它本身包含基于unsortedList的所有项目保存分组的子列表,因此返回的sortedList可能具有: [[],[a,n,t],[red,eye],[toad,roar,flap],[closer,smarter,faster]]

我理解各个逻辑步骤,但是通过未排序列表的实际迭代,使用评估然后创建具有单独分组子列表的sortedList就在我之外。我通过查看完整的代码示例来学习,但我在这里找不到任何可以学习的内容,所以任何帮助都会受到赞赏。抱歉这篇冗长的帖子。

2 个答案:

答案 0 :(得分:1)

如果我理解正确的问题,您希望将unsorted_list转换为列表列表,其中每个列表仅包含相等长度的值。这可以这样实现:

from collections import defaultdict

unsorted_list = ['a', 'n', 't', 'red', 'eye', 'toad', 'roar', 'flap']

def group_strings_by_length(lst):
    grouped = defaultdict(list)

    for s in lst:
        grouped[len(s)].append(s)
    return list(grouped.values())

grouped_strings = group_strings_by_length(unsorted_list)  
print(grouped_strings)  #[['a', 'n', 't'], ['red', 'eye'], ['toad', 'roar', 'flap']]

答案 1 :(得分:1)

此代码将找到列表中最长的字母,创建另一个列表,并将每个单词排序到其存储桶中。我还修改了你的读入循环,不需要一种奇怪的检查方式

def wordList():
    unsortedList=[]
    promptUser=input("Type words, one at a time. When you are done, type stop: ")  

    while promptUser !="stop":
        unsortedList.append(promptUser)
        promptUser = input("Type words, one at a time. When you are done, type stop: ")


    sortedList = []
    #will go from 0 up to and including length of longest letter in your list 
    for x in range(0,max([len(x) for x in unsortedList])+1):
        #Creates an empty entry
        sortedList.append([])
        #Goes through an unsorted list
        for s in unsortedList:
            #If length of a word is equal to x it adds it to its bucket
            if len(s) == x:
                sortedList[x].append(s)
    print(sortedList)


Input: ['a', 'eye', 'flap', 'n', 'red', 'roar', 't', 'toad']
Output: [[], ['a', 'n', 't'], [], ['eye', 'red'], ['flap', 'roar', 'toad']]
相关问题