【问题标题】:Modify a list by deleting the first element通过删除第一个元素来修改列表
【发布时间】:2017-12-16 06:59:36
【问题描述】:

我不明白我做错了什么。我从这段代码收到的输出不正确。

通过删除第一个元素并将最后一个元素更改为 Joe 来修改 short_names。给定程序的示例输出:['Sam', 'Ann', 'Joe']

short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']
"Your solution here"
print(short_names)

我的代码:

short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']

short_names.pop()
short_names.sort()

print(short_names)

【问题讨论】:

  • short_names.sort() 对列表进行排序,您应该将最后一个元素更改为 short_names[-1] = "Joe"
  • 您熟悉索引吗?
  • 另请注意 list.pop() 从列表的 back 中删除,而不是在前面。 Python 将列表的末尾视为堆栈的顶部。

标签: python python-3.x


【解决方案1】:
user_input = input() 
short_names = user_input.split()

del short_names[0]       # delete the first element
short_names[2] = "Joe"   # change the last element to Joe

print(short_names)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

另一种方式:

  short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']  
  short_names[-1] = 'Joe'  
  short_names = short_names[1:len(short_names)]  
  print(short_names)  

【讨论】:

    【解决方案3】:

    您想在索引 0(第一项)处弹出。不指定索引,默认为最后一个索引。

    short_names.pop(0)
    

    而要修改最后一项,只需修改索引-1处的列表。

    short_names[-1] = "Joe"
    

    【讨论】:

    • 这是您的代码输出 ['Sam', 'Ann', 'Joseph'] 预期输出 ['Sam', 'Ann', 'Joe']
    • @SHRIYADAHAL 您需要修改列表的最后一个元素:short_names[-1] = "Joe"
    • @ChristianDean 谢谢,我错过了问题的那一部分
    • @abccd 考虑一下,即使你早些时候纠正了我关于 this answer 的问题;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多