Zip Python Array?

时间:2015-05-12 05:38:53

标签: python arrays

我有一个很大的阵列:

[['I love these vitamins so far', 'and my doctor recommended the 5000IU 
dosage', 'Love the product!  Power Vitamin with my Power Drink!', 'Great 
Product - Works Great!', 'Love all that goes into this vitamin D!', 'great 
product', 'Best Vitamin D3', 'Great product! You will not be disappointed.', 
'Doctor prescribed', 'Made in the USA'], ['MusicLova', 'Mg', 'Rosie', 'Stacey 
Chillemi "Author Stacey Chillemi"', 'Denise', 'jim easley', 'Betterlife', 
'Martin A. Leddy', 'Angela Wright', 'Bob Jama'], 
['http://www.amazon.com/gp/pdp/profile/A3HJLBNJMSQBQ5', etc .. 
reviews/R2AQ19W7L9D2SP', 'www.amazon.com/gp/customer-reviews/R28OFZC87A7XIM', 
'www.amazon.com/gp/customer-reviews/R33AMKSHD88B0Q'], 1, 'NatureWise']

我想在每个数组中应用2个元素。我想创建一个数组数组,内部数组只是每个列表中的一个元素?我认为使用zip是最简单的方法,但我得到太多项目解压缩?

zip(data) 

例如,我想:

   [["I love these vitamins so far", "MusicLova", 
   'http://www.amazon.com/gp/pdp/profile/A3HJLBNJMSQBQ5', 1, "NatureWise"] ..        
    etc ]

并且所有列表都具有相同的元素数,除了不在数组

中的最后2个元素

2 个答案:

答案 0 :(得分:3)

如果我理解正确,应该这样做:

>>> x = [[1,2,3],['a','b','c'],'me','you']
>>> [list(i)+x[-2:] for i in zip(*x[:-2])]

>>> [[1, 'a', 'me', 'you'], [2, 'b', 'me', 'you'], [3, 'c', 'me', 'you']]

答案 1 :(得分:1)

如果输入准备得恰当,

zip()将起作用,例如:

x = [['I love these vitamins so far', 'and my doctor recommended the 5000IU dosage', 
'Love the product!  Power Vitamin with my Power Drink!', 
'Great Product - Works Great!'], ['MusicLova', 'Mg', 'Rosie', 'Stacey Chillemi'], 
['www.amazon.com/gp/pdp/profile/A3HJLBNJMSQBQ5', 
'www.amazon.com/gp/customer-reviews/R2AQ19W7L9D2SP', 
'www.amazon.com/gp/customer-reviews/R28OFZC87A7XIM', 
'www.amazon.com/gp/customer-reviews/R33AMKSHD88B0Q'], 1, 'NatureWise']

x[-1] = [x[-1]]*len(x[0])
x[-2] = [x[-2]]*len(x[0])

print(list(zip(*x)))

...输出为:

[('I love these vitamins so far', 'MusicLova', 'www.amazon.com/gp/pdp/profile/A3HJLBNJMSQBQ5', 1, 'NatureWise'), ('and my doctor recommended the 5000IU dosage', 'Mg', 'www.amazon.com/gp/customer-reviews/R2AQ19W7L9D2SP', 1, 'NatureWise'), ('Love the product! Power Vitamin with my Power Drink!', 'Rosie', 'www.amazon.com/gp/customer-reviews/R28OFZC87A7XIM', 1, 'NatureWise'), ('Great Product - Works Great!', 'Stacey Chillemi', 'www.amazon.com/gp/customer-reviews/R33AMKSHD88B0Q', 1, 'NatureWise')]