Python 函数:遍历“key:value”字典,并根据字典的键将最后一个“value”单词附加到输出字符串中

Python Function: Loop Through a "Key:Value" Dictionary And Append The Last "Value" Word To an Output String Based on the Dictionary's Key

提问人:PineNuts0 提问时间:9/15/2023 最后编辑:PineNuts0 更新时间:9/15/2023 访问量:61

问:

假设我有以下字典:

sorted_dict = {1: 'You', 2: 'teeth', 3: 'are', 4: 'mood', 5: 'test', 6: 'helpful'} 

每个单词都与一个数字相关联,我想将单词排列成金字塔,如下例所示:

1
2 3
4 5 6  

这里的诀窍是我只想要与每行末尾的数字(1、3、6)相对应的单词。所有其他单词都被丢弃。所以:

1: You
3: are
6: helpful

最后,我想返回一个与数字 1、3、6 关联的字符串。在我的示例中,所需的输出将是:

"You are helpful"

我已经开始尝试为此编写函数(见下文)。但是我不知道如何在我的循环中获取金字塔模式 1、3、6 以输出正确的单词。请注意,这是一个小例子,但我希望我的函数(具有这种金字塔模式)在可能包含数千个单词的字典上运行。

def test(input_list):
    output_str = ""
    
    i = 1
    
    for key, value in sorted_dict.items():
        
        print(key, value)
        
        # i += ? 
        # if statement here to only append string to output_str if it equals the right i number 
        output_str += ' ' + value
        
    
    return output_str

我上面的当前函数返回:这是不正确的' You teeth are mood test helpful'

如何解决此问题?

python 函数 循环字 数字序列

评论

1赞 Barmar 9/15/2023
模式是 , , , ...11+21+2+3
0赞 PineNuts0 9/15/2023
我在数学上理解了这种模式......但是代码方面,如何使用 i 计数迭代器捕获它?
1赞 Michael Cao 9/15/2023
您可以使用该公式获取第 i 个单词的所需键。另外,如果你只是使用自然数作为键,为什么不只使用列表呢?i * (i+1) / 2

答:

3赞 Barmar 9/15/2023 #1

您无需遍历字典。使用简单的算术生成键,顺序为 、 、 等。当在字典中找不到密钥时停止。11+21+2+3

key = 1
increment = 2
output_list = []

while key in sorted_dict:
    output_list.append(sorted_dict[key])
    key += increment
    increment += 1

output_str = " ".join(output_list)

评论

0赞 PineNuts0 9/15/2023
感谢您的回复。您的代码针对我的字典进行了测试,产生了“You teeth mood”,这不是我想要的。我无法生成自己的密钥。键值对字典给了我,我必须按原样使用它。
0赞 Barmar 9/15/2023
我认为它现在应该可以工作了,我的起始增量是错误的。
0赞 PineNuts0 9/16/2023
成功了!多么优雅的解决方案......谢谢!