【问题标题】:Python 3.3 list assistancePython 3.3 列表帮助
【发布时间】:2015-08-25 04:09:51
【问题描述】:

我正在尝试编写一个基本上要求用户输入 5 个名称的代码。然后它将创建这些名称的列表,并将它们打印出来。随后,它打印列表的排序版本。接下来,代码将打印列表中的第三个名称。在这一步之后,代码询问用户要更改哪个名称,然后用户为他们选择替换的名称输入一个新名称。

这应该是输出,例如:

名字是:"Sal", "Jane", "Fred", "Bob", "Cole"

排序后的名字是:"Bob", "Cole", "Fred", "Jane", "Sal"

列表中的第三个名字是:"Fred"(这将是排序列表中的第三个名字)

名称是:"Bob", "Joe", "Fred", "Jane", "Sal"(假设用户选择替换第二个名称。

到目前为止,这就是我所拥有的代码:

name_list = input ("Please list 5 names here:")
name_list = name_list.split()
name_list = [name_list]
print ("The names in your list are:", name_list)
print ("The sorted list is:", name_list)
print(name_list[2:3])

我遇到的问题是,我无法弄清楚为什么排序列表没有正确“排序”,其次,最后一行应该打印出第三个名称,而是打印[]。

【问题讨论】:

  • 如果要排序,请使用sorted(name_list),如果要按索引获取第三项,请使用names_list[2]

标签: python list sorting


【解决方案1】:

首先,在打印出排序列表之前你没有对列表进行排序,你应该在打印排序列表之前调用name_list.sort()。

其次,name_list[<start>:<end>] 打印出从 <start> index 开始到 <end> - 1 index 结束的列表,因此您将得到 name_list[2:3] 的空列表。你应该改用name_list[2]。

【讨论】:

    【解决方案2】:

    它没有排序,因为你没有对它进行排序,你只是把它放在另一个列表中。只需致电name_list.sort()。

    切片[2:3] 不起作用,因为在调用name_list = [name_list] 之后,它是一个包含单个元素的列表,它本身就是一个名称列表。该列表在索引 2 中没有元素,因此当您对它进行切片时会返回一个空列表。

    【讨论】:

    • 所以我解决了我遇到的问题,现在我需要找到一种方法来询问用户他们想要替换哪个名称,然后让输入替换它。
    【解决方案3】:
    name_list=input("enter the list of names ")
    name_list.sort()
    print "sorted name list is ",name_list
    print "Third name is ",name_list[2:3]
    item= input("enter the name to be modified ")
    print "position of the name to be modified is",name_list.index(item)
    print("enter a name to modify "+item+ "!")
    newname= input("name: ")
    position=name_list.index(item)
    name_list[position]=newname
    name_list.sort()
    print"modifified list is ",name_list
    

    【讨论】:

      【解决方案4】:

      这应该可行。

      name_list = input ("Please list 5 names here:")
      name_list = name_list.split()
      print ("The names in your list are:", name_list)
      print ("The sorted list is:", name_list.sort())  #sorting list
      print(name_list[2])   # printing 3rd element of the list as indices start from 0
      

      要查找要替换的元素的索引(例如“Fred”),您可以这样做:

      index_to_be_replaced = name_list.index("Fred")
      

      一旦找到索引就执行:

      name_list[index_to_be_replaced] = new_element to be inserted
      

      【讨论】:

      • 谢谢,现在我只需要找到一种方法让用户选择要替换的名称并在那里输入替换它。
      • name_list = [i for i in name_list] 是多余的。
      猜你喜欢
      • 2017-08-22
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2018-08-31
      • 2010-09-29
      • 2023-01-26
      • 2012-02-21
      相关资源
      最近更新 更多