list1=[1.0,2.0,3.1,4.2]
list2=[3.0,2.0,7.2,5.1,9.2]
list3=[2.1,4.2,5.1,9.2]
su1 = list1 + [x for x in list2 if x not in list1]
su2= su1 + [x for x in list3 if x not in su1]
su2=sorted(su2)
print su2
我可能会有更多列表,所以我想自动化我的代码。
list_of_lists= []
list_of_lists.append(list1)
list_of_lists.append(list2)
list_of_lists.append(list3)
我创建了list_of lists
。但是要知道怎么循环呢?
答案 0 :(得分:3)
# Your lists goes here
list1 = [1.0, 2.0, 3.1, 4.2]
list2 = [3.0, 2.0, 7.2, 5.1, 9.2]
list3 = [2.1, 4.2, 5.1, 9.2]
# Collect all the lists
list_of_lists = []
list_of_lists.append(list1)
list_of_lists.append(list2)
list_of_lists.append(list3)
# This list will contain the final result
result = []
# Loop the inner lists from list_of_lists, this will be list1, list2, list3...
for inner_list in list_of_lists:
# Loop each element of the inner lists
for element in inner_list:
# Make sure the element is not already in the result (this can also be done with sets)
if element not in result:
# Add the inner element to result
result.append(element)
# Sort the result
result = sorted(result)
# Finally output the list
print result # Outputs: [1.0, 2.0, 2.1, 3.0, 3.1, 4.2, 5.1, 7.2, 9.2]
答案 1 :(得分:2)
import itertools
su2 = sorted(set(itertools.chain(*list_of_lists))
itertools.chain
会返回一个生成器,该生成器依次迭代每个列表的元素,itertools.chain(*list_of_lists)
与x for lst in list_of_lists for x in lst
在这里做同样的事情。
set
比检查每个新值是否已经在列表中更有效地对它们进行重复数据删除
最后,sorted
按照现有代码对其进行排序。