Python列表未排序

Python列表未排序,python,xml,list,sorting,Python,Xml,List,Sorting,列表仍按迭代顺序打印 我想按列表每行的第一个字符的字母顺序排序 #!/usr/bin/env python3 import xml.etree.ElementTree as ET tree = ET.parse('A00.xml') root = tree.getroot() for w in root.iter('w'): lemma = w.get('hw') pos = w.get('pos') tag = w.get('c5') myList = (w.

列表仍按迭代顺序打印

我想按列表每行的第一个字符的字母顺序排序

#!/usr/bin/env python3
import xml.etree.ElementTree as ET
tree = ET.parse('A00.xml')
root = tree.getroot()

for w in root.iter('w'):
    lemma = w.get('hw')
    pos = w.get('pos')
    tag = w.get('c5')
    myList = (w.text + "\t" + lemma + "\t" + pos + "\t" + tag)
    sorted(myList)
    print(myList)
AttributeError:“str”对象没有属性“sort”

所以我想有一个字符串列表并按每个字符串的第一个字符排序,但是字符串是不可变的,所以我有一个排序错误

myList.sort(key = lambda ele : ele[1])
印刷品(样本):

期望的:

can can VERB    VM0
I   i   PRON    PNP
have    have    VERB    VHB
in  in  PREP    PRP
recent  recent  ADJ AJ0
years   year    SUBST   NN2
edited  edit    VERB    VVD
a   a   ART AT0
self-help   self-help   ADJ AJ0
journal     journal SUBST   NN1
for     for PREP    PRP
people  people  SUBST   NN0

更新答案:

您的问题是您试图对
str
进行排序,而不是对
列表进行排序。字符串不可排序。也许你想做这样的事情:

a   a   ART AT0
can can VERB    VM0
edited  edit    VERB    VVD
for     for PREP    PRP
have    have    VERB    VHB
I   i   PRON    PNP
in  in  PREP    PRP
journal     journal SUBST   NN1
people  people  SUBST   NN0
recent  recent  ADJ AJ0
self-help   self-help   ADJ AJ0
years   year    SUBST   NN2
这将为您提供字符串中所有字符的排序列表。如果要将它们连接回字符串,可以使用:

myList = sorted(list(w.text + "\t" + lemma + "\t" + pos + "\t" + tag))
print(myList)
旧答案:

sorted
返回已排序的列表,它不修改原始列表。如果要对列表进行适当排序,请使用
sort
功能:

print(''.join(myList))

名称错误:名称“排序”不正确defined@pglove,修正了。它是列表本身的一个函数。对不起,对不起,我不明白。我一直在说“排序没有定义”@pglove,哦,我明白了
myList
实际上是一个
str
。这是这里的根本问题。是的,不确定问题是什么。当我打印我的列表时,它打印得很好,为什么我不能将这些字符串发送到列表中并按每个字符串的第一个字符进行排序?不是重复的,这里的问题是OP试图在
str
上调用sort。
print(''.join(myList))
for w in root.iter('w'):
    ...
    myList.sort()
    print(myList)