python删除列表元素并返回,Python:如何从字典中删除元素并将其作为列表返回?...

博客内容涉及一个Python编程问题,作者尝试从包含单词的字典中移除长度小于或等于7个字符的单词。在尝试使用`pop`方法时遇到了错误。解决方案指出应使用`new_list.index(word)`为参数调用`pop`方法,以根据索引删除元素,而非直接使用字符串。经过修改后的代码能够正确地从字典的值列表中移除指定长度的单词。
摘要由CSDN通过智能技术生成

I have been trying an exercise that requires me to remove words in a dictionary containing words that are 7 or fewer characters long. So far I have tried using the .values() method to get only the words within the square brackets, and thus create a list to store these words. However, I am having a problem with using the pop method where I get

"TypeError: 'str' object cannot be interpreted as an integer".

Here is my code :

word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],

'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack']}

def main():

edited_synonyms = remove_word(word_dict)

print(edited_synonyms)

def remove_word(word_dict):

synonyms_list = word_dict.values()

new_list = []

for i in synonyms_list:

new_list.extend(i)

for word in new_list:

letter_length = len(word)

if letter_length <= 7:

new_list.pop(word)

return new_list

main()

解决方案

Your program is right. Any ways you need to add index value in pop.

Modified code:

>>> def remove_word(word_dict):

synonyms_list = word_dict.values()

new_list = []

for i in synonyms_list:

new_list.extend(i)

for word in new_list:

letter_length = len(word)

if letter_length <= 7:

new_list.pop(new_list.index(word)) # Modified line

return new_list

Output:

>>> main()

['exhibit', 'communicate', 'manifest', 'disclose', 'unhurried', 'leisurely', 'behind', 'slack']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值