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

Python 3.6 - separating the columns in multiple lists into new lists

这是我的代码,它计算唯一数字出现的次数并查找列表 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')]

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

谢谢!

那个怎么样:

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')]

从您的代码继续

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')]

您可以使用列表理解

>>> 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']]