如何使我的第二个列表以正确的字顺序显示?

时间:2015-11-29 10:42:41

标签: python python-3.x

我正在使用Python 3.4。

这是我的代码:

varSentence = input("What sentence would you like to convert to numbers?" )

varList = varSentence.split()
print (varList)
varList2 = list(set(varList))
print (varList2)

for varCount, varWord in enumerate(varList2):

    for varWord2 in varList:

        if varWord2 == varWord:
            varWord2 = varCount
            print (varCount + 1)

输入:

varSentence = "this is a test for stack over flow this is a test for stack overflow"

varList = varSentence.split()
 varList2  = ['this', 'is', 'a', 'test', 'for', 'stack', 'over', 'flow', 'overflow']

预期产出:

[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9]

2 个答案:

答案 0 :(得分:0)

我认为您只想将varList中的单词添加到varList2(如果它们尚未存在),然后在varList2中打印其排名。你可以一次完成所有事情:

varSentence = input("What sentence would you like to convert to numbers?" )

varList = varSentence.split()
print (varList)
varList2 = []
ranks = []

for word in varList:
    if word in varList2:
        i = varList2.index(word)
        ranks.append(i+1)
    else:
        varList2.append(word)
        ranks.append(len(varList2))

print varList2
for i in rank:
    print rank

答案 1 :(得分:0)

如果要维护原始列表中元素的顺序,请使用OrderedDict:

from collections import OrderedDict
varList2 = list(OrderedDict.fromkeys(varList))
# -> ['this', 'is', 'a', 'test', 'for', 'stack', 'over', 'flow', 'overflow']

根据您的预期输出结合使用Counter dict是最好的方法,将counts * ind附加到列表中,以下为您提供O(n)解决方案,而不是您的自己的二次方法:

varList = [ 'this', 'is', 'a', 'test', 'for', 'stack', 'over', 'flow', 'this', 'is', 'a', 'test', 'for', 'stack', 'overflow']


from collections import OrderedDict, Counter
counts = Counter(varList)
od = OrderedDict.fromkeys(varList, 0)
res = []
for ind, k in enumerate(od, 1):
    res.extend([ind] *  counts[k])

print(res)

输出:

[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9]

如果您只想打印输出,只需删除列表res:

for ind, k in enumerate(od, 1):
    print(*[ind]*v,end=" ")

输出:

1 1 2 2 3 3 4 4 5 5 6 7 8 8 9