2017-06-02 41 views
2
x_list = ["I", "live", "in", "New", "-", "York", "City", ".", "I", "am" "from", "New", "-", "Delhi"] 

這是我的列表。我想要加入連字符「 - 」前後的單詞。這樣我的名單就變成了。如何連接符合特定標準的列表元素?

x_list = ["I", "live", "in", "New-York", "City", ".", "I", "am", "from", "New-Delhi"] 

是否有一個簡短的方法來做到這一點?

+0

此列表是如何創建的?在分詞之前處理這個問題可能會更容易。 – asongtoruin

+2

也不會調用你的變量'list' – asongtoruin

+0

不幸的是,這是在一個數據集中,我希望清理它。如果這是正常的文本,我可以很容易地使用正則表達式來正確標記它們。 – Djokester

回答

2

您可以將enumerate d for -loop:

lst = ["I", "live", "in", "New", "-", "York", "City"] 
for index, item in enumerate(lst): 
    if item == '-': 
     lst[index-1:index+2] = [''.join(lst[index-1:index+2])] 

print(lst) # ['I', 'live', 'in', 'New-York', 'City'] 

或者,如果你與短名單和幾個'-'(在你的例子一樣)打交道你也可以使用一個while循環。然而,這有二次運行時的行爲,所以如果你關心性能不使用這個對於很多'-'大名單:

lst = ["I", "live", "in", "New", "-", "York", "City"] 
while '-' in lst: 
    pos = lst.index('-') 
    lst[pos-1:pos+2] = [''.join(lst[pos-1:pos+2])] 

print(lst) # ['I', 'live', 'in', 'New-York', 'City'] 
+2

第一個版本是連字符數的二次方。 – enedil

+0

@enedil是的,這就是爲什麼我還包括第二個版本:)你認爲在答案中需要更明顯的警告嗎? – MSeifert

+0

我相信如此。軟件工程師(尤其是初學者)對這些問題並不謹慎。 – enedil

4

有點怪異,但優雅的方式:

lst = ["I", "live", "in", "New", "-", "York", "City"] 

pattern = "<erpvinpervin>" 
s = pattern.join(lst) 
s = s.replace("{0}-{0}".format(pattern), "-") 
lst = s.split(pattern) 

由於pattern你可以使用任何不可能在列表中滿足的任意字符串。

0
for index, item in enumerate(lista): 
    if item == '-': # Checks if current item is your separator 
     lista[index-1] = ''.join(lista[index-1:index+2]) # Joins the 3 indexes (new-york or whatever.) 
     lista.remove(lista[index]) # Removes the "garbage" that remained from the actual list 
     lista.remove(lista[index]) 

可能有更好的方法做到這一點,但這個工作正常,很容易理解。

相關問題