对从文件中读取的列表进行排序?

2024-07-04 05:43:07 发布

您现在位置:Python中文网/ 问答频道 /正文

def insertionSort(a):
    for i in range(1, len(a)): #outer loop covering the range
        value = a[i] #value = to list, which will compare items to the left
        i = i - 1 #i goes lower than index to compare further to the left
        while i >= 0 : #keep comparing till its at the beginning of the list
            if value < a[i]: #if value is less than i
                a[i+1] = a[i] # shift number in right i to slot i + 1
                a[i] = value # shift value that was left into slot i
                i = i - 1
            else:
                break

infile = open("file1.txt", "r")
a=[]
for aline in infile:
    a = aline.split()

insertionSort(a)
print(a)

这是文件中的内容:

7686850495948548545

如何让insertionSort()函数处理文件?你知道吗


Tags: thetoinforifshiftvaluerange
2条回答

你的问题之一是你反复分配给a。那不是你想要的。现在,首先给a分配一个空列表。然后,每次替换之前分配给a的内容时,您都会将每一行分解分配给a。我认为你真正想要的是:

a.extend(aline.split())

解决这个问题,然后让我们知道你的代码运行得有多好。你知道吗

这部分不太正确。你知道吗

infile = open("file1.txt", "r")
a=[]
for aline in infile:
    a = aline.split()

打开和读取(或写入)文件的首选方式如下:

with open('some_file.txt', 'r') as in_file:
  string_numbers = in_file.read()

然后,一旦你把数字放在一个字符串中,你就可以把它们分成一个列表,如下所示:

nums_list = list(string_nums)

所以nums_list现在是一个字符串列表,使用列表理解将它们转换为int:

nums = [int(num) for num in nums_list]

编辑:

只是为了好玩,这里有一个简明的版本:

with open('filename.txt') as in_file:
  nums = [int(n) for n in list(in_file.read().strip())]

.strip()添加只是为了确保没有奇怪的空格转换。你知道吗

相关问题 更多 >

    热门问题