列出索引超出范围,使用sort(key = lambda)进行索引

时间:2020-09-19 21:14:40

标签: python sorting lambda text-files

所以我正在读取一个文件,该文件要按cy和cx元素排序。我正在读取的文本文件看起来像这样。

<circle r="36" class="dot" cx="2150" cy="750" fill="#abae3b" style="fill: rgb(0, 82, 72);"></circle>
<circle r="36" class="dot" cx="2950" cy="1350" fill="#e1e25b" style="fill: rgb(0, 82, 72);"></circle>
<circle r="36" class="dot" cx="2250" cy="2250" fill="#babd44" style="fill: rgb(0, 82, 72);"></circle>
<circle r="36" class="dot" cx="550" cy="1750" fill="#5a610d" style="fill: rgb(0, 82, 72);"></circle>
<circle r="36" class="dot" cx="950" cy="1550" fill="#70761a" style="fill: rgb(0, 82, 72);"></circle>
<circle r="36" class="dot" cx="650" cy="1950" fill="#606610" style="fill: rgb(195, 252, 241);"></circle>
<circle r="36" class="dot" cx="1350" cy="1050" fill="#858a26" style="fill: rgb(0, 82, 72);"></circle>

python代码正在尝试从文本文件中读取内容,并根据cy值和cx值对它进行排序。

data=[]
with open(r"SomeSpaceInMemory.txt","r") as datafile:
    for line in datafile:
        data.append(line)

data.sort(key=lambda n: (n.split()[4],n.split()[3]))

运行此代码时出现此错误:

Traceback (most recent call last):
  File "file.py", line 7, in <module>
    data.sort(key=lambda n: (n.split()[4],n.split()[3]))
  File "file.py", line 7, in <lambda>
    data.sort(key=lambda n: (n.split()[4],n.split()[3]))
IndexError: list index out of range

当行被分割时,它应该看起来像这样,所以我不知道为什么索引超出范围。

['<circle', 'r="36"', 'class="dot"', 'cx="450"', 'cy="1850"', 'fill="#555c0a"', 'style="fill:', 
'rgb(0,', '82,', '72);"></circle>']

感谢您的帮助!

0 个答案:

没有答案