2016-05-31 53 views
-1
String = "ask not what your country can do for you ask" 
words = ["ask","not","what","your","country","can","do","for","you","ask"] 
positions = [1,2,3,4,5,6,7,8,9,1] 

我需要用單詞和位置重新創建原始字符串。它不能引用回到原來的字符串從它的單詞列表中重新創建句子(不重複)和位置

String = "ask not what your country can do for you ask" 
words = ["ask","not","what","your","country","can","do","for","you","ask"] 
positions = [1,2,3,4,5,6,7,8,9,1] 

for word in String(): 
    if not word in words: 
     words.append(word) 
    i = words.index(word) 
    positions.append(i) 

s = "" 
for i in positions: 
    s = s + words[i] + " " 

print(s) 

我可以重新創建判決,但我必須使用原始字符串

+0

它通過獨特的詞來重新創建和職位 – User999822

+0

你確定你的變量'單詞'正確嗎?這似乎不符合你說的話。此外,你試圖解決這個問題的是什麼? – DainDwarf

+0

歡迎來到Stack Overflow!所有發佈的內容都是程序說明。但是,我們需要您[提問](// stackoverflow.com/help/how-to-ask)。堆棧溢出不是免費的代碼寫入服務。請[編輯]您的帖子以包含我們可以回答的有效問題。提醒:請確保你知道[這裏的主題是什麼](// stackoverflow.com/help/on-topic),要求我們爲你編寫程序,而且建議是無關緊要的。 –

回答

0

這個答案:

String = "ask not what your country can do for you ask" 
words = String 
list_word = String.split() 
res=[] 
dict_word={} 
for i, j in enumerate(list_word): 
    if j in dict_word: 
     res.append(dict_word[j]) 
    else: 
     dict_word[j]=i 
     res.append(i) 
print words 
print res 


ask not what your country can do for you ask 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 0] 
相關問題