2013-04-08 38 views
-3

我在Python中有一個列表,我想獲取列表中的所有單詞,但是以x的塊爲單位。從列表中獲取每個X字

例子:

my_list = ["This" "is" "an" "example" "list" "hehe"] 
counter = 3 

那就需要輸出:

["This" "is" "an"], ["example" "list" "hehe"] 

謝謝:)

+0

你的函數應該帶一個列表和一個計數器。在函數中,創建列表(空)和列表(空)以及整數current_count(0)的列表。當current_count小於計數器時,追加到您的空列表。當它溢出時,將其設置爲0並將列表追加到列表的列表中。當您用完條目時,請返回您的列表清單。 – Patashu 2013-04-08 04:40:53

+1

您的列表只有一個項目。由於你在列表中省略了逗號,所以字符串被連接了。 – 2013-04-08 04:51:48

回答

1
>>> my_list = ["This", "is", "an", "example", "list", "hehe"] 
>>> counter = 3 
>>> zip(*[iter(my_list)] * counter) 
[('This', 'is', 'an'), ('example', 'list', 'hehe')] 

在Python3,您需要將結果轉換的zip()list

>>> list(zip(*[iter(my_list)] * counter)) 
[('This', 'is', 'an'), ('example', 'list', 'hehe')] 

您可以使用mapitertools.izip_longest如果列表是不使用itertools.islice()計數器的多個

>>> my_list = ["This", "is", "an", "example", "list", "hehe", "onemore"] 
>>> map(None, *[iter(my_list)] * counter) 
[('This', 'is', 'an'), ('example', 'list', 'hehe'), ('onemore', None, None)] 


>>> from itertools import izip_longest 
>>> list(izip_longest(*[iter(my_list)] * counter, fillvalue = '')) 
[('This', 'is', 'an'), ('example', 'list', 'hehe'), ('onemore', '', '')] 
+0

謝謝,我該如何做呢?例如列表中有7個項目,並且剩下一個單詞? – VEDYL 2013-04-08 08:54:20

+0

@VEDYL,它會被截斷 - 你只能得到前6個項目。很容易改變這個使用itertools.izip_longest或地圖 – 2013-04-08 09:23:21

1

你可以試試這個簡單的代碼:

my_list = ["This" "is" "an" "example" "list" "hehe"] 
counter = 3 
result = [] 

for idx in range(0, len(my_list), counter): 
    print my_list[idx: idx +counter] 
    result.append(my_list[idx: idx+counter]) 

print result 
1

In [20]: from math import ceil 

In [21]: from itertools import islice 

In [22]: lis=["This", "is", "an", "example", "list", "hehe"] 

In [23]: it=iter(lis) 

In [24]: [list(islice(it,3)) for _ in xrange(int(ceil(len(lis)/3)))] 
Out[24]: [['This', 'is', 'an'], ['example', 'list', 'hehe']] 
+0

你忘了導入'ceil' – jamylak 2013-04-08 07:19:54

+0

@jamylak謝謝,修正了這一點。 – 2013-04-08 13:39:00

0

另一種方法是使用產生的結果,所以你可以讓他們在這將消除向外方括號的需求,並允許其他一些自由,想偷懶加載

幾乎一樣Artsiom Rudzenka的,但給你想完全輸出。

def slicer(l, step): 
    for i in range(0, len(l), step): 
     yield l[i:i+step] 

my_list = ["This", "is", "an", "example", "list", "hehe"] 

print(', '.join(str(x) for x in slicer(my_list, 3))) 

請注意,它不需要它返回的外部列表,它會根據需要返回每個子列表。在這種情況下,我們只是使用它來創建一個生成器,只需將它與','結合起來就可以得到您在答案中查找的確切輸出。