python - 如何自动化我的 Python 代码?

标签 python list

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]

关于python - 如何自动化我的 Python 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35846053/

相关文章:

python - 根据条件在 Dataframe 中乘以多列的最快方法

python - python中的线程: retrieve return value when using target=

python - 切片时的 if 语句

python - 如何根据计算的索引显示循环列表

python - 了解 Python 中的数据封装

python - 你能覆盖python中的循环名称吗

python - 用新文件名替换python中的文件名

java - ArrayList在自定义列表类Java中实现

Python字符串分割连接4

python - 如何将字符串列表转换为整数列表 - 很多事情似乎不起作用