【问题标题】:Getting " 'str' object does not support item assignment" Error from Python3 [duplicate]获取“'str'对象不支持项目分配”来自Python3的错误[重复]
【发布时间】:2021-08-10 13:19:57
【问题描述】:

我尝试使用文本文件作为 Python 中快速排序函数的输入。事实证明,我得到了这个错误

TypeError: 'str' object does not support item assignment

我知道错误的发生是因为 Python 中的字符串是不可变的,因此它们无法更改。但是,我不确定如何修复我的代码以使其运行。

我的代码(在 Python 3 中)

import sys
f = open('C:/Users/.../.../Desktop/Test/test1.txt')
array = str(f.read())

def QuickSort(array, starting= 0, ending=len(array)-1):
   
    if starting < ending:
       
       p = Partition(array, starting, ending)
       
       QuickSort(array, starting, p-1)
       Quicksort(array, p+1, ending)
   
def Partition(array, starting, ending):
       Pivo_Index = starting
       Pivot = array[Pivot_Index]
   
       while starting < ending:
           while starting < len(array) and array[starting] <= Pivot:
               starting += 1
           
           while array[ending] > Pivot:
               ending -= 1
           
           if starting < ending:
               array[starting], array[ending] = array[ending], array[starting]
           
       array[ending], array[Pivot_Index] = array[Pivot_Index], array[ending]
       
       return ending

print(QuickSort(array))

我的文本文件如下

12.11.1990 a
01.01.1991 aa
02.02.1992 baa
02.02.1992 aaa
15.07.1999 ytyvm

关于如何修复我的代码的建议?

【问题讨论】:

    标签: python arrays string typeerror quicksort


    【解决方案1】:

    read() 返回一个字符串,该字符串是不可变的(因此,如您所见,无法排序)。如果您想获取文件中的行列表并对其进行排序,您可以使用array = f.readlines()

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2011-07-26
      • 2016-10-27
      相关资源
      最近更新 更多