解决以下问题时: “假设您有一个随机的字符串列表(例如:a、b、c、d、e、f、g),请编写一个程序按字母顺序对字符串进行排序。 您不能使用排序命令。”
我遇到了通过以下代码运行字符串的问题,这有时会使我在最终列表中出现重复的字符串
我是 python 的新手,我们的类(class)刚刚开始研究 numpy 和该模块中的函数,我不确定代码中是否使用了任何函数(排序函数除外)。
import numpy as np
list=[]
list=str(input("Enter list of string(s): "))
list=list.split()
print() # for format space purposes
listPop=list
min=listPop[0]
newFinalList=[]
if(len(list2)!=1):
while(len(listPop)>=1):
for i in range(len(listPop)):
#setting min=first element of list
min=listPop[0]
if(listPop[i]<=min):
min=listPop[i]
print(min)
listPop.pop(i)
newFinalList.append(min)
print(newFinalList)
else:
print("Only one string inputted, so already alphabatized:",list2)
["a","y","z"]的预期结果
["a","y","z"]
实际结果...
输入字符串列表:a y z
一个 A A ['一个', '一个', '一个']
输入字符串列表:d e c
d C d d ['c', 'd', 'd']
最佳答案
选择排序:对于列表的每个索引i
,选择i
处或之后的最小项,并将其交换到第i
位置。这是三行的实现:
# For each index i...
for i in range(len(list)):
# Find the position of the smallest item after (or including) i.
j = list[i:].index(min(list[i:])) + i
# Swap it into the i-th place (this is a no-op if i == j).
list[i], list[j] = list[j], list[i]
list[i:]
是list
的切片(子集),从第i
元素开始。min(list)
为您提供list
中的最小元素。list.index(element)
为您提供list
中element
的(第一个)索引。a, b = b, a
自动交换a
和b
的值。
此实现中最棘手的部分是,当您使用 index
查找最小元素的索引时,您需要在相同的 list[i:] 中找到该索引
您在其中找到该元素的切片,否则您可能会在列表的较早部分选择重复的元素。由于您正在查找相对于 list[i:]
的索引,因此您需要将 i
添加回它以获取整个 list< 中的索引
.
关于python - 如何在没有任何排序函数的情况下按字母顺序对字符串数组进行排序? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58618404/