2017-04-15 48 views
-1

我有類似試圖更改列表格式在Python

[['b c', 'd e', 'f'], ['b', 'c', 'd', 'e', 'f'], ['b c', 'd', 'b', 'e', 'g', 'f']] 

,但我想

['(b c) d e f', 'b c d e f', '(b c) d b e g f'] 

我已經嘗試了幾種不同的東西,這個切換到,但括號是搞亂了我做法。我能夠加入沒有括號的字符串。有沒有簡單的方法在Python中做到這一點?

+4

是什麼決定時,括號中應該出現的邏輯,當他們不應該?我對第一個列表中爲什麼'd e'不加括號的問題感到特別困惑。 – Blckknght

+1

在第一個子列表中,不清楚爲什麼'(b c)'是在parens中,而不是'd e' –

回答

0

這個工作對我來說:

new_list = [" ".join(words if not " " in words else "({})".format(words) for words in seq) for seq in original_list] 

但承擔括號中的邏輯是,每當有串在一個空間中加入了它們加入。但這意味着你的例子是不正確的。如果parentheres只應添加到第一個字符串中的每個子列表,然後你必須包括在有條件的計數:

new_list = [" ".join(words if not " " in words and i == 0 else "({})".format(words) for i, words in enumerate(seq)) for seq in original_list]