我需要转置以下python列表。
`data = (
['1002','1','10'],
['1002','2','20'],
['1002','3','30'],
['1004','1','30'],
['1004','2','40'],
['1004','3','60'])`
需要转换为
`(['1002'],['1','2','3'],['10','20','30'],
['1004'],['1','2','3'],['30','40','60']) `
我尝试了这样的python嵌套列表推导:
`[[row[i] for row in data] for i in range(3)]`
它不起作用。我将所有值都放在一行中。
我需要根据行的第一个元素将其分解。
任何建议都表示赞赏。
谢谢
答案 0 :(得分:0)
你的名单是扁平的,不是嵌套的,所以我们要做的第一件事就是将所有东西分成三组
zip(*[iter(data)]*3)
然后我们可以创建一个字典,我们将在其中构建列表。
from collections import defaultdict
d = defaultdict(list)
for a, b, c in zip(*[iter(data)]*3):
d[a].append(b)
d[a].append(c)
print([(k,) + tuple(v) for k, v in d.items()])
#[('1002', '1', '10', '2', '20', '3', '30'), ('1004', '1', '30', '2', '40', '3', '60')]
然后我们只是从该字典构建输出。
编辑:根据更改,我们将修改我们在dict中存储值的方式
data = (
['1002','1','10'],
['1002','2','20'],
['1002','3','30'],
['1004','1','30'],
['1004','2','40'],
['1004','3','60'])
d = defaultdict(list)
for a, b, c in data:
d[a].append((b, c))
output = []
for k, v in d.items():
output.append([k])
a, b = map(list, zip(*v))
output.append(a)
output.append(b)
print(output)
#[['1002'], ['1', '2', '3'], ['10', '20', '30'], ['1004'], ['1', '2', '3'], ['30', '40', '60']]
答案 1 :(得分:0)
让我知道列表理解是否必须使用。
data = ['1002','1','10', '1002','2','20', '1002','3','30', '1004','1','30', '1004','2','40', '1004','3','60']
res = []
for index in range(0,len(data),9):
res.append(data[index:index + 9])
final = []
for item in res:
x = []
for element in item:
if element not in x:
x.append(element)
final.append(x)
print(final)
答案 2 :(得分:0)
由于你需要按第一个元素聚合,我会考虑使用itertools.groupby
(https://docs.python.org/3.6/library/itertools.html#itertools.groupby):
import itertools
data = [
['1002','1','10'],
['1002','2','20'],
['1002','3','30'],
['1004','1','30'],
['1004','2','40'],
['1004','3','60']]
result = [
[[key] + list(map(list, zip(*[row[1:] for row in rows])))]
for key, rows in itertools.groupby(data, lambda row: row[0])
]
print(result)
[[['1002', ['1', '2', '3'], ['10', '20', '30']]], [['1004', ['1', '2', '3'], ['30', '40', '60']]]]