2011-08-11 21 views
0

我有這個信息的字典:對於在dictonary項目,拆一個項目的名稱,添加和刪除一些信息蟒蛇

x = {Country:{City:Population},.....} 

但城市名稱現在是這樣的:Country_City_Neighbourhood_Population(出於某種原因) 。我需要刪除所有的信息,並保持這樣的城市和社區:CityNeighbourhood

我這樣做:

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] 

,但我沒有獲得任何合理的結果。

回答

1

嘗試是這樣的:

for country in x: 
    for city, pop in x[country].iteritems(): 
     if 'Ecuador' in city: 
      print ''.join(city.split('_')[1:3]) 
+0

謝謝你們......你永遠是最棒的! :) – Alejandro

+0

整潔:遍歷'x.items()'並移除'x [country]'lookup – katrielalex

4
"".join(city.split("_")[1:-1]) 
  • city.split("_")給出了 「城市」 由 「_」 分隔的單詞列表。
  • [1:-1]slices列表中刪除第一個和最後一個元素
  • "".join連他們重新走到一起,用空字符串中
  • 之間
+0

謝謝!但你的意思是我必須這樣做: city3 =「」.join(city.split(「_」)[1:-1])????? – Alejandro

+0

@Alejandro:如果你想......你可以隨你的喜好來做任何你喜歡的事情。也許你想'在x國家:x [country] =「」.join(x [country] .split(「_」)[1:-1])'? – katrielalex

+0

謝謝@katrielatex !!!! – Alejandro

相關問題