擅长:python、mysql、java
<p>试试这个</p>
<pre><code>#Define all the categories
dogs = ['husky', 'chihuahua', 'labrador', 'beagle']
flowers = ['dandelion', 'rose', 'tulip']
colours = ['blue', 'yellow', 'green', 'red', 'pink', 'orange']
#The Input String
outOfOrder = "husky tulip red orange"
#Split up the string into an array which each word seperated
outOfOrderArray = outOfOrder.split()
#Array to hold all words of each category
orderedArray = [[], [], [], []]
#loop through all the words in the array
for word in outOfOrderArray:
#Check if the word is in each category.
if word in dogs:
orderedArray[2].append(word)
elif word in flowers:
orderedArray[1].append(word)
elif word in colours:
orderedArray[0].append(word)
#If its not in the array, do whatever you want with it. I jsut stuck them at the end.
else:
orderedArray[3].append(word)
orderedString = ""
#Combine all the words in ordered Array to create a final string
for category in orderedArray:
for word in category:
orderedString = orderedString + word + " "
print(orderedString)
</code></pre>