我需要在名为' vetor'的列表中以正确的顺序添加用户的输入。我尝试使用备份,但我停在那里,因为当我打印备份时,它甚至都没有完成。谢谢您的所有时间!
这是我的代码:
vetor = ["alvaro", "beto", "carlos", "rodrigo"]
back = []
nome = input("Digite o nome: ")
for x in range(len(vetor)):
if vetor[x] == nome[0:len(vetor[x])] and len(vetor[x]) < len(nome):
back.append(vetor[x])
back.append(nome)
if vetor[x][0:len(nome)] == nome and len(vetor[x]) > len(nome):
back.append(nome)
back.append(vetor[x])
if ord(vetor[x][0]) < ord(nome[0]):
back.append(vetor[x])
elif len(vetor[x]) < len(nome):
for n in range(len(vetor[x])):
if ord(nome[n]) == ord(vetor[x][n]) and ord(nome[n+1]) < ord(vetor[x][n+1]):
back.append(nome)
back.append(vetor[x])
elif ord(nome[n+1]) > ord(vetor[x][n+1]):
back.append(vetor[x])
elif len(vetor[x]) > len(nome):
for n in range(len(nome)):
if ord(nome[n]) == ord(vetor[x][n]) and ord(nome[n+1]) < ord(vetor[x][n+1]):
back.append(nome)
back.append(vetor[x])
elif ord(nome[n]) == ord(vetor[x][n]) and ord(nome[n+1]) > ord(vetor[x][n+1]):
back.append(vetor[x])
&#13;
印刷(背)
答案 0 :(得分:2)
列表中是否有足够的名称
vetor = sorted(vetor + [nome])
是不可能的?如果没有,请使用它。当你意识到它太慢时,你可以随时进行优化。
否则,如果您愿意,可以使用bisect
module提供将内容插入排序列表的方法:
>>> import bisect
>>> vetor = ["alvaro", "beto", "carlos", "rodrigo"]
>>> bisect.insort(vetor, "bob")
>>> vetor
['alvaro', 'beto', 'bob', 'carlos', 'rodrigo']
>>> bisect.insort(vetor, "dave")
>>> vetor
['alvaro', 'beto', 'bob', 'carlos', 'dave', 'rodrigo']
答案 1 :(得分:1)
除非您必须实施自己的排序例程,否则请使用sorted(iterable)
,如下所示:
vetor = ["alvaro", "beto", "carlos", "rodrigo"]
print sorted(vetor) # Returns a new sorted list
nome = input("Digite o nome: ") # Ok, if you are using python3, use raw_input if you are using python2.
vetor.append(nome)
print sorted(vetor) # Returns a new sorted list with the new item appended.
答案 2 :(得分:0)
看起来您的列表已经排序了。您可以使用bisect module将其插入正确的位置。一种选择是使用bisect.insort_left,如下所示。您可以在模块中查看其他选项。
>>> import bisect
>>> vetor = ["alvaro", "beto", "carlos", "rodrigo"]
>>> bisect.insort_left(vetor, "new name")
>>> vetor
['alvaro', 'beto', 'carlos', 'new name', 'rodrigo']
>>>
答案 3 :(得分:0)
这有帮助吗?
vetor = ["alvaro", "beto", "carlos", "rodrigo"]
nome = raw_input("Digite o nome: ") # for python 2
n = len(vetor)
i = 0
while i < n:
if nome < vetor[i]: break
i = i+1
vetor = vetor[0:i] + [nome] + vetor[i:]
print vetor