元组列表中的2项

时间:2016-02-17 05:51:57

标签: python python-2.7

我有一个元组列表:

Items = [(4, 2), (1, 1), (2, 4), (8, 6), (11, 4), (10, 2), (7, 3), (6, 1)]

我希望在for循环中得到它:

NewItems = [[(4, 2), (1, 1)], 
            [(2, 4), (8, 6)],
            [(11, 4), (10, 2)],
            [(7, 3), (6, 1)]]

我这样做了:

NewItems = []
while len(Items) > 0:
    NewItems.append([Items[0], Items[1]])
    del Items[0:2]
print NewItems

我认为这不是最好的方式,因为我删除了Items个变量。 然后我试着这样做:

newList = iter(Items)
NewItems = []
for a, b in zip(newList, newList):
    NewItems.append([a, b])
print NewItems

但那是合并元组的。

有没有更好的解决方案可以做同样的事情?

6 个答案:

答案 0 :(得分:4)

如果你不介意元组的元组而不是内部列表,只需将其压缩:

>>> zip(Items[0::2], Items[1::2])
[((4, 2), (1, 1)), ((2, 4), (8, 6)), ((11, 4), (10, 2)), ((7, 3), (6, 1))]

答案 1 :(得分:3)

您可以使用列表推导来成对压缩项目。

Items = [(4, 2), (1, 1), (2, 4), (8, 6), (11, 4), (10, 2), (7, 3), (6, 1)]
New_Items = [list(pair) for pair in zip(Items[::2], Items[1::2])]

>>> New_Items
[[(4, 2), (1, 1)], [(2, 4), (8, 6)], [(11, 4), (10, 2)], [(7, 3), (6, 1)]]

答案 2 :(得分:2)

>>> items = [(4,2),(1,1),(2,4),(8,6),(11,4),(10,2),(7,3),(6,1)]
>>> new_items = [items[i:i+2] for i in range(0, len(items), 2)] 
>>> new_items
[[(4, 2), (1, 1)], [(2, 4), (8, 6)], [(11, 4), (10, 2)], [(7, 3), (6, 1)]]

你可以像这样使用while循环。

>>> new_items = []
>>> while items:
...     new_items.append((items.pop(0), items.pop(0)))
... 
>>> new_items
[((4, 2), (1, 1)), ((2, 4), (8, 6)), ((11, 4), (10, 2)), ((7, 3), (6, 1))]

然而,这对items具有破坏性,并且由于使用pop(0)(即O(n)

而非常有效

答案 3 :(得分:2)

怎么样

Items = [(4,2),(1,1),(2,4),(8,6),(11,4),(10,2),(7,3),(6,1)]

NewItems = []
j =0   
for i in xrange(1,len(Items)-1): 
    if j+1 > len(Items):
        break
    NewItems.append([Items[j],Items[j+1]])
    j += 2

print NewItems

答案 4 :(得分:1)

from time import time

Items = [(4,2),(1,1),(2,4),(8,6),(11,4),(10,2),(7,3),(6,1)]
NewItems = []
start_time = time()
while len(Items) > 0 :
    NewItems.append([Items[0],Items[1]])
    del Items[0:2]
print NewItems
print time() - start_time

Items = [(4,2),(1,1),(2,4),(8,6),(11,4),(10,2),(7,3),(6,1)]
NewItems = []
start_time = time()
for i in range(len(Items) / 2):
    NewItems.append([Items[2*i],Items[2*i + 1]])
print NewItems
print time() - start_time

通过一些时间安排,您可以验证第二个解决方案是否更快

答案 5 :(得分:0)

又一种方法,但可能不是最漂亮的。

x = []
i = iter(Items)

while True:
    try:
        x.append([i.next(), i.next()])
    except StopIteration:
        break