Python 列表列表比较
Python list of lists comparison
我有两个以下类型的列表:
A=[[a1,b1,c1],[d1,e1,f1]]
B=[[a2,b1,c2],[d2,e1,f2]]
我希望能够生成这样的列表 C:
C=[[a1,b1,c1,a2,c2],[d1,e1,f1,d2,f2]]
有什么想法吗?
您可以使用 zip()
函数获取列,然后使用 collections.OrderedDict
保留具有先前顺序的唯一元素:
>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> [d.fromkeys(i+j).keys() for i,j in zip(A,B)]
[['a1', 'b1', 'c1', 'a2', 'c2'], ['d1', 'e1', 'f1', 'd2', 'f2']]
作为列表理解:
import operator
c = [sorted(list(set(a + b)), key=operator.itemgetter(1, 0)) for a, b in zip(A, B)]
或者作为一个循环:
import operator
results = []
for a, b in zip(A, B):
uniques = list(set(a + b))
# Here we do two sorts in one call:
results.append(sorted(uniques, key=operator.itemgetter(1, 0)))
print(results)
[['a1', 'b1', 'c1', 'a2', 'c2'], ['d1', 'e1', 'f1', 'd2', 'f2']]
这个解决方案不需要排序也不需要索引
C = [ea+[e for e in eb if e not in ea] for ea,eb in zip(A,B)]
它产生
[['a1', 'b1', 'c1', 'a2', 'c2'], ['d1', 'e1', 'f1', 'd2', 'f2']]
C = []
# zip the lists to be able to loop through both
# at the same time.
# make from A and B sets to be able to make a union of
# A and B. Convert the union set to list to sort it and
# to append to the main list
for i, (m, n) in enumerate(zip(A,B)):
C.append(sorted(list(set(A[i]) | set(B[i]))))
print(C)
**output**
[['a1', 'a2', 'b1', 'c1', 'c2'], ['d1', 'd2', 'e1', 'f1', 'f2']]
我有两个以下类型的列表:
A=[[a1,b1,c1],[d1,e1,f1]]
B=[[a2,b1,c2],[d2,e1,f2]]
我希望能够生成这样的列表 C:
C=[[a1,b1,c1,a2,c2],[d1,e1,f1,d2,f2]]
有什么想法吗?
您可以使用 zip()
函数获取列,然后使用 collections.OrderedDict
保留具有先前顺序的唯一元素:
>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> [d.fromkeys(i+j).keys() for i,j in zip(A,B)]
[['a1', 'b1', 'c1', 'a2', 'c2'], ['d1', 'e1', 'f1', 'd2', 'f2']]
作为列表理解:
import operator
c = [sorted(list(set(a + b)), key=operator.itemgetter(1, 0)) for a, b in zip(A, B)]
或者作为一个循环:
import operator
results = []
for a, b in zip(A, B):
uniques = list(set(a + b))
# Here we do two sorts in one call:
results.append(sorted(uniques, key=operator.itemgetter(1, 0)))
print(results)
[['a1', 'b1', 'c1', 'a2', 'c2'], ['d1', 'e1', 'f1', 'd2', 'f2']]
这个解决方案不需要排序也不需要索引
C = [ea+[e for e in eb if e not in ea] for ea,eb in zip(A,B)]
它产生
[['a1', 'b1', 'c1', 'a2', 'c2'], ['d1', 'e1', 'f1', 'd2', 'f2']]
C = []
# zip the lists to be able to loop through both
# at the same time.
# make from A and B sets to be able to make a union of
# A and B. Convert the union set to list to sort it and
# to append to the main list
for i, (m, n) in enumerate(zip(A,B)):
C.append(sorted(list(set(A[i]) | set(B[i]))))
print(C)
**output**
[['a1', 'a2', 'b1', 'c1', 'c2'], ['d1', 'd2', 'e1', 'f1', 'f2']]