Python 3.3列表帮助

时间:2015-06-10 04:49:58

标签: python list sorting

我正在尝试编写一个基本上要求用户输入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])

我遇到的问题是一个,我无法弄清楚为什么排序列表不排序"排序"正确,其次,最后一行应打印出第三个名称,但打印[]代替。

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

这应该有用。

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
相关问题