Python List没有排序

时间:2018-04-21 14:46:11

标签: 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.text + "\t" + lemma + "\t" + pos + "\t" + tag)
    sorted(myList)
    print(myList)

列表仍按迭代顺序打印。

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

myList.sort(key = lambda ele : ele[1])

属性错误:' str'对象没有属性'排序'

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

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)
    print(myList)

打印(样本):

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

所需:

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

2 个答案:

答案 0 :(得分:0)

更新答案:

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

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

这将为您提供字符串中所有字符的排序列表。如果要将它们连接回字符串,可以使用:

print(''.join(myList))

旧答案:

sorted 返回排序列表,它不会修改原始列表。如果要对列表进行就地排序,请使用sort函数:

for w in root.iter('w'):
    ...
    myList.sort()
    print(myList)

答案 1 :(得分:0)

sorted返回一个列表,而sort在其中执行

myList = sorted(myList)

myList.sort()