Python 3.6 - 将多个列表中的列分成新列表

时间:2017-08-22 13:38:36

标签: python list reformat

这是我的代码,它计算唯一数字出现的次数,并查找在列表A中重复5次的数字,然后在列表A中重复2次,并打印列表A的任何匹配的结果与列表B中的对应值相对应。列表A和B的大小始终相同。

a = (['12','12','12','12','12','23','24','24','31','31'])
b = (['1','2','2','2','2','2','5','5','5','5'])

from collections import Counter
counts = Counter(a)

c = []

for ai , bi in zip(a,b):
   if counts[ai] == 5:
       c.append([ai,bi])
   elif counts[ai] == 1:
       c.append([ai,bi])
   else:
       None

print(c)
#[['12', '1'], ['12', '2'], ['12', '2'], ['12', '2'], ['12', '2'], ['23', '2']]

是否有快速方法,以便我的代码可以将多个输出列表重新格式化为如下所示的列表:

#[('12', '12', '12', '12', '12', '23'), ('1', '2', '2', '2', '2', '2')]

这样每个列表中的每一列都可以有自己的列表。

谢谢!

3 个答案:

答案 0 :(得分:2)

那是怎么回事:

import itertools

c = [['12', '1'], ['12', '2'], ['12', '2'], ['12', '2'], ['12', '2'], ['23', '2']]

merged = list(itertools.chain(*c))
# merged = ['12', '1', '12', '2', '12', '2', '12', '2', '12', '2', '23', '2']

split = [tuple(merged[::2]), tuple(merged[1::2])]
# split = [('12', '12', '12', '12', '12', '23'), ('1', '2', '2', '2', '2', '2')]

答案 1 :(得分:1)

继续您的代码

c = [['12', '1'], ['12', '2'], ['12', '2'], ['12', '2'], ['12', '2'], ['23', '2']]

cols = [] #initialize list of columns
for i in range(2):
  tup = tuple([item[i] for item in c]) #create tuple from loop of column
  cols.append(tup)
print(cols) # [('12', '12', '12', '12', '12', '23'), ('1', '2', '2', '2', '2', '2')]

答案 2 :(得分:1)

您可以使用列表理解

>>> x = [['12', '1'], ['12', '2'], ['12', '2'], ['12', '2'], ['12', '2'], ['23', '2']]
>>> [tuple(v[0] for v in x), tuple(v[1] for v in x)]
[('12', '12', '12', '12', '12', '23'), ('1', '2', '2', '2', '2', '2')]

以最初想要的格式保存数据可能更有效。元组是不可变的,因此使用列表并附加到它们会更容易。类似的东西:

columns = []
values = []

for ai , bi in zip(a,b):
   if counts[ai] == 5:
       columns.append(ai)
       values.append(bi)
   elif counts[ai] == 1:
       columns.append(ai)
       values.append(bi)

print([columns, values])

# prints this
[['12', '12', '12', '12', '12', '23'], ['1', '2', '2', '2', '2', '2']]
相关问题