首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将x个长度为x的单词添加到不同的嵌套列表中

如何将x个长度为x的单词添加到不同的嵌套列表中
EN

Stack Overflow用户
提问于 2019-01-16 02:19:45
回答 4查看 463关注 0票数 2

我有一项工作,需要根据单词的长度将单词添加到相应的列表中。也就是说,所有长度为1的单词将进入列表1,长度为2的单词将进入列表2,依此类推……

下面是我目前拥有的代码。如你所见,我已经创建了一个带有L个空存储桶的列表,其思想是让每个长度的单词都有对应的存储桶。这就是我被卡住的地方。如果不知道将有多少个存储桶,我不知道如何添加它们。我对Python非常陌生,任何帮助都将不胜感激!

代码语言:javascript
复制
def empty_buckets(n): 
    """Return a list with n empty lists. Assume n is a positive integer. """ 
    buckets = [] 
    for bucket in range(n): 
        buckets.append([]) 
    return buckets 

计算所有单词的最大长度L。

代码语言:javascript
复制
longest = ''
    for L in words:
        if len(L) > len(longest):
            longest = L
    return longest

创建一个包含L个空列表(存储桶)的列表。

代码语言:javascript
复制
buckets = empty_buckets(L)
EN

回答 4

Stack Overflow用户

发布于 2019-01-16 02:37:39

您可以使用max()并提供len的键函数来获取单词列表中最长的单词。

您可以为“空”单词再创建一个存储桶,并使用for循环将所有单词排序到存储桶中,并使用len(word)将所有单词索引到存储桶中

代码语言:javascript
复制
# create some demo strings and add some other words
words = [ str(10**k) for k in range(10)]
words.extend(["this","should","work","out","somehow"])

print(words)  # ['1', '10', '100', '1000', '10000', '100000', '1000000', '10000000',
              #  '100000000', '1000000000', 'this', 'should', 'work', 'out', 'somehow']

longest = len(max(words,key=len)) # get the length of the longest word

# create a empty bucket for "" and one bucket for length 1 up to longest
bins = [None] + [ [] for _ in range(longest+1)]  

# loop over words and put then in the bin at index len(word)
for w in words:
    bins[len(w)].append(w)

print(bins)

输出:

代码语言:javascript
复制
[None, ['1'], ['10'], ['100', 'out'], ['1000', 'this', 'work'], ['10000'], 
       ['100000', 'should'], ['1000000', 'somehow'], ['10000000'], 
       ['100000000'], ['1000000000']]

Doku:

票数 0
EN

Stack Overflow用户

发布于 2019-01-16 03:06:07

buckets = [0] * longest # this will make a list of longest size

然后,在每个元素中创建一个列表,我使用列表的第一个元素来记录该存储桶的计数。

for i in range(longest): buckets[i] = [0]

然后,您需要将单词添加到桶中。

for L in words: buckets[len(L)][0] += 1 # increasing the count of that bucket buckets[len(L)].append(L) # Adding the word to that bucket

下面是一个示例:

代码语言:javascript
复制
longest = 10
words = ['this', 'that', 'foremost']
buckets = [0] * longest # this will make a list of longest size 
for i in range(longest):
   buckets[i] = [0]
for L in words:
   buckets[len(L)][0] += 1 # increasing the count of that bucket
   buckets[len(L)].append(L) # Adding the word to that bucket 

要访问任何计数,只需使用buckets[number][0],而要访问所有单词,可以从buckets[number][1]开始循环该计数。

票数 0
EN

Stack Overflow用户

发布于 2019-01-16 07:19:42

正如我之前在评论中提到的,我使用字典来解决这个问题。

在这里,您不需要使用任何外部函数创建空列表,因为我们不知道实际长度。

所以你可以尝试这样做。

您可以访问https://rextester.com/ZQKA28350在线运行代码。

代码语言:javascript
复制
def add_words_to_bucket(words): 
    d = {}

    for word in words: 
        l = len(word)
        if l in d: 
            d[l].append(word) 
        else: 
            i = 0
            while l >= 0 and not l in d:
                if not i: 
                    d[l] = [word]
                else: 
                    d[l] = []
                l = l - 1
                i += 1
    return d

def get_as_list(d): 
    bucket = [d[i] for i in range(0, len(d))]
    return bucket


words = ["a",  "git", "go", "py", "java", "paper", "ruby", "r"]
d = add_words_to_bucket(words) 
bucket = get_as_list(d)
print(d) # {0: [], 1: ['a', 'r'], 2: ['go', 'py'], 3: ['git'], 4: ['java', 'ruby'], 5: ['paper']}
print(bucket) # [[], ['a', 'r'], ['go', 'py'], ['git'], ['java', 'ruby'], ['paper']]


words2 = ["a",  "git", "go", "py", "", "java", "paper", "ruby", "r","TheIpMan", ""]
d2 = add_words_to_bucket(words2)
bucket2 = get_as_list(d2)
print(d2) # {0: ['', ''], 1: ['a', 'r'], 2: ['go', 'py'], 3: ['git'], 4: ['java', 'ruby'], 5: ['paper'], 6: [], 7: [], 8: ['TheIpMan']}
print(bucket2) # [['', ''], ['a', 'r'], ['go', 'py'], ['git'], ['java', 'ruby'], ['paper'], [], [], ['TheIpMan']]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54204739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档