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



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

最新更新