I have a dictionary with this info:
开发者_运维百科x = {Country:{City:Population},.....}
but City name is now like: Country_City_Neighbourhood_Population
(for some reason). I need to remove all the information and just keep the City and Neighbourhood like this: CityNeighbourhood
.
I did this:
for country in x:
for city, pop in x[country].iteritems():
isCountry = city.split("_").count("Ecuador")
if isCountry > 0:
city1 = city.split("_")
city1.remove("Ecuador")
city2 = city1[0:-1]
city3 = ""
for i in range(len(city2)-1):
city3 = city3 + city2[i]
but I didn't obtain any reasonable result.
"".join(city.split("_")[1:-1])
city.split("_")
gives a list of the words in "city" separated by "_".[1:-1]
slices the list to remove the first and last elements"".join
connects them back together, with the empty string in between
Try something like this:
for country in x:
for city, pop in x[country].iteritems():
if 'Ecuador' in city:
print ''.join(city.split('_')[1:3])
精彩评论