Skip to main content
 首页 » 编程设计

python之如何自动化我的 Python 代码

2025年05月04日28zhwl

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。但是知道怎么做,如何遍历它?

请您参考如下方法:

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