2017-10-06 109 views
1

给出名称时,例如Aberdeen ScotlandPython如何将每个字母放到一个单词中?

我需要得到Adbnearldteoecns的结果。

将第一个单词简单化,但将最后一个单词倒过来放在第一个单词之间。

到目前为止,我已经做了:

coordinatesf = "Aberdeen Scotland" 

for line in coordinatesf: 
    separate = line.split() 
    for i in separate [0:-1]: 
     lastw = separate[1][::-1] 
     print(i) 
+1

停止使用您使用的编辑器标记算法问题。 –

回答

0

有点脏,但它的工作原理:

coordinatesf = "Aberdeen Scotland" 
new_word=[] 
#split the two words 

words = coordinatesf.split(" ") 

#reverse the second and put to lowercase 

words[1]=words[1][::-1].lower() 

#populate the new string 

for index in range(0,len(words[0])): 
    new_word.insert(2*index,words[0][index]) 
for index in range(0,len(words[1])): 
    new_word.insert(2*index+1,words[1][index]) 
outstring = ''.join(new_word) 
print outstring 
0

注意你想要做的是只有当输入字符串是由明确的两个相同长度的单词。 我使用断言来确保这是真实的,但你可以将它们排除在外。

def scramble(s): 
    words = s.split(" ") 
    assert len(words) == 2 
    assert len(words[0]) == len(words[1]) 
    scrambledLetters = zip(words[0], reversed(words[1])) 
    return "".join(x[0] + x[1] for x in scrambledLetters) 

>>> print(scramble("Aberdeen Scotland")) 
>>> AdbnearldteoecnS 

您可以使用sum()替换x [0] + x [1]部分,但是我认为这会降低可读性。

0

这会分割输入,将第一个单词与相反的第二个单词相拉,加入对,然后加入对的列表。

coordinatesf = "Aberdeen Scotland" 
a,b = coordinatesf.split() 
print(''.join(map(''.join, zip(a,b[::-1])))) 
相关问题