2013-07-17 58 views
2

我有一個列表,在一個類似的格式如下:如何返回Python的列表中的每個第n項?

list1 = ['random words go', 'here and','the length varies','blah', 
     'i am so confused', 'lala lala la'] 

什麼代碼將是適當的返回列表中的每一個第三個項目,其中包括第一個字?這是預期的輸出:

["random", "here", "length", "i", "confused", "la"] 

我想我應該使用拆分功能,但我不知道如何做到這一點。有人也可以解釋我如何做到這一點,所以整個列表不是像這樣的「零件」?相反,如果這有意義,我怎麼能把它變成一個長列表。

+0

的[Python化的方式在一個更大的列表中返回第n個的每個項目的列表(可能重複http://stackoverflow.com/questions/1403674/pythonic返回列表中的每一個第n個項目在一個更大的列表) – dnozay

+0

@dnozay不完全,OP是解釋它很糟糕,雖然。 –

+0

是的,我現在看到,其他問題對於問題的一部分仍然非常相關。 – dnozay

回答

5

這可能是最可讀的方式做到這一點:

>>> list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la'] 
>>> result = ' '.join(list1).split()[::3] 
['random', 'here', 'length', 'i', 'confused', 'la'] 

或沒有再次加入和分裂名單:

from itertools import chain 
result = list(chain.from_iterable(s.split() for s in list1))[::3] 

那麼你可以加入結果:

>>> ' '.join(result) 
'random here length i confused la' 
+1

@BedSheets'''.join(...)' –

3

尋找:

list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la'] 

from itertools import chain, islice  
sentence = ' '.join(islice(chain.from_iterable(el.split() for el in list1), None, None, 3)) 
# random here length i confused la 
+0

@BedSheets更新爲包含'''.join'' –

0

另一個存儲效率的版本

>>> list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la'] 
>>> from itertools import chain, islice 
>>> ' '.join(islice(chain.from_iterable(map(str.split, list1)), 0, None, 3)) 
'random here length i confused la' 
1
[word for item in list1 for word in item.split()][0::3] 
0

把它變成一個長長的清單:

>>> list6 = [] 
>>> for s in list1: 
... for word in s.split(): 
...  list6.append(word) 
... 
>>> list6 
['random', 'words', 'go', 'here', 'and', 'the', 'length', 'varies',  'blah', 'i', 'am', 'so', 'confused', 'lala', 'lala', 'la'] 
>>> 

然後,你可以做切片與[:: 3]

建議
>>> list6[::3] 
['random', 'here', 'length', 'i', 'confused', 'la'] 

如果你想在一個字符串中:

>>> ' '.join(list6[::3]) 
'random here length i confused la' 
>>>> 
+0

根據更新的請求添加了連接 – AnnaRaven

0

試試這個:

>>> list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la'] 
>>> result = ' '.join(list1).split()[::3] 
['random', 'here', 'length', 'i', 'confused', 'la'] 
相關問題