2013-04-08 79 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))) 

请注意,它不需要它返回的外部列表,它会根据需要返回每个子列表。在这种情况下,我们只是使用它来创建一个生成器,只需将它与','结合起来就可以得到您在答案中查找的确切输出。