[英]How to make my second list appear in correct word order?
我正在使用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]
我认为您只是想将单词从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
如果要维护原始列表中元素的顺序,请使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.